@criogaid/pi-hashline-edit 0.11.0 → 0.13.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 (94) hide show
  1. package/LICENSE +1 -0
  2. package/README.md +73 -17
  3. package/README.zh-CN.md +74 -18
  4. package/package.json +8 -7
  5. package/src/core/AGENTS.md +2 -2
  6. package/src/core/apply.test.ts +15 -2
  7. package/src/core/apply.ts +6 -10
  8. package/src/core/case-fold.test.ts +16 -25
  9. package/src/core/case-fold.ts +4 -4
  10. package/src/core/character-set.test.ts +1 -6
  11. package/src/core/character-set.ts +7 -61
  12. package/src/core/regex.ts +2 -32
  13. package/src/core/replace.test.ts +51 -0
  14. package/src/core/replace.ts +10 -4
  15. package/src/core/search-analysis.test.ts +66 -61
  16. package/src/core/search-analysis.ts +24 -39
  17. package/src/core/search-matrix.test.ts +2 -2
  18. package/src/core/search-matrix.testing.ts +6 -16
  19. package/src/core/search-schema.ts +0 -1
  20. package/src/core/search.test.ts +6 -19
  21. package/src/core/search.ts +10 -8
  22. package/src/index.ts +28 -3
  23. package/src/integration/config-registration.test.ts +77 -4
  24. package/src/integration/fusion-dispatch.test.ts +47 -2
  25. package/src/integration/grep-errors.test.ts +31 -0
  26. package/src/integration/grep-flags.test.ts +13 -196
  27. package/src/integration/grep-js-completeness.test.ts +41 -8
  28. package/src/integration/grep-line-candidates.test.ts +4 -33
  29. package/src/integration/grep-matrix.test.ts +1 -1
  30. package/src/integration/grep-path-matrix.test.ts +59 -65
  31. package/src/integration/grep-prefilter-coverage.test.ts +26 -8
  32. package/src/integration/grep-process-limits.test.ts +46 -0
  33. package/src/integration/grep-regex.test.ts +7 -2
  34. package/src/integration/grep-rg.test.ts +106 -12
  35. package/src/integration/grep-translation.test.ts +14 -7
  36. package/src/integration/model-budget-lifecycle.test.ts +41 -2
  37. package/src/integration/npm-package.test.ts +12 -10
  38. package/src/integration/npm-package.testing.ts +147 -1
  39. package/src/integration/replace-package.testing.ts +2 -2
  40. package/src/integration/report-replay.test.ts +4 -0
  41. package/src/pi/AGENTS.md +23 -15
  42. package/src/pi/action-fusion.test.ts +38 -4
  43. package/src/pi/action-fusion.ts +23 -19
  44. package/src/pi/argument-diagnostics.ts +28 -48
  45. package/src/pi/argument-validation.test.ts +103 -6
  46. package/src/pi/argument-validation.ts +55 -31
  47. package/src/pi/budgets.ts +19 -10
  48. package/src/pi/config.test.ts +1 -1
  49. package/src/pi/diagnostic-buffer.test.ts +1 -0
  50. package/src/pi/edit-tool.ts +3 -3
  51. package/src/pi/execute.test.ts +4 -0
  52. package/src/pi/failure-context.test.ts +24 -3
  53. package/src/pi/failure-context.ts +36 -42
  54. package/src/pi/failure-path.test.ts +8 -3
  55. package/src/pi/file-commit.test.ts +109 -52
  56. package/src/pi/file-commit.ts +62 -56
  57. package/src/pi/fusion-card.ts +12 -7
  58. package/src/pi/grep-candidates.test.ts +5 -5
  59. package/src/pi/grep-candidates.ts +80 -48
  60. package/src/pi/grep-matrix.test.ts +14 -29
  61. package/src/pi/grep-order.test.ts +132 -9
  62. package/src/pi/grep-output.ts +173 -48
  63. package/src/pi/grep-render.ts +40 -34
  64. package/src/pi/grep-rg.testing.ts +9 -6
  65. package/src/pi/grep-scope.ts +51 -29
  66. package/src/pi/grep-search.ts +96 -71
  67. package/src/pi/grep-tool.ts +28 -34
  68. package/src/pi/grep.test.ts +348 -83
  69. package/src/pi/model-budgets.test.ts +56 -6
  70. package/src/pi/model-budgets.ts +7 -4
  71. package/src/pi/mutation-result.test.ts +25 -1
  72. package/src/pi/mutation-result.ts +7 -2
  73. package/src/pi/mutation-runner.ts +4 -5
  74. package/src/pi/output-budgets.test.ts +3 -1
  75. package/src/pi/path.ts +18 -4
  76. package/src/pi/pi.test.ts +22 -0
  77. package/src/pi/read-delegation.test.ts +119 -0
  78. package/src/pi/read-tool.ts +109 -61
  79. package/src/pi/read.test.ts +351 -17
  80. package/src/pi/regex-worker.test.ts +42 -0
  81. package/src/pi/regex-worker.ts +17 -11
  82. package/src/pi/registration.test.ts +157 -102
  83. package/src/pi/render.test.ts +97 -0
  84. package/src/pi/render.ts +9 -9
  85. package/src/pi/replace-tool.ts +5 -2
  86. package/src/pi/report-schema.ts +75 -37
  87. package/src/pi/report.test.ts +73 -31
  88. package/src/pi/report.ts +12 -5
  89. package/src/pi/rg-process.ts +41 -5
  90. package/src/pi/rg-regex.test.ts +12 -39
  91. package/src/pi/rg-regex.ts +31 -79
  92. package/src/pi/text-stream.test.ts +3 -0
  93. package/src/pi/text-stream.ts +1 -1
  94. package/src/testing/regex-translation-corpus.ts +39 -96
@@ -4,14 +4,15 @@ import assert from "node:assert/strict";
4
4
  import { mkdir, mkdtemp, rm, readFile, writeFile } from "node:fs/promises";
5
5
  import { tmpdir } from "node:os";
6
6
  import { join } from "node:path";
7
- import { initTheme } from "@earendil-works/pi-coding-agent";
7
+ import { pathToFileURL } from "node:url";
8
+ import { createReadToolDefinition, initTheme } from "@earendil-works/pi-coding-agent";
8
9
  import type { Theme } from "@earendil-works/pi-coding-agent";
9
10
  import { validateToolArguments } from "@earendil-works/pi-ai";
10
11
  import { makeReadOverride } from "./tool-factories.testing.ts";
11
12
  import { computeLineHash } from "../core/hash.ts";
12
13
  import { callTool } from "./tool-call.testing.ts";
13
14
  import { DEFAULT_CONFIG } from "./tool-factories.testing.ts";
14
- import { formatByteSize } from "./budgets.ts";
15
+ import { formatByteSize, outputBudgetsFor } from "./budgets.ts";
15
16
  import { DEFAULT_OUTPUT_BUDGETS } from "./tool-factories.testing.ts";
16
17
  import { reportOf } from "./report.ts";
17
18
  import { createAnchorFormatter } from "./anchor-format.ts";
@@ -34,18 +35,119 @@ const stubTheme = { fg: (_k: string, s: string) => s, bold: (s: string) => s } a
34
35
 
35
36
  initTheme();
36
37
 
37
- test("read execute: text outputs LINE#HASH│content", async () => {
38
+ test("read anchors omitted, true, or null → preserves anchored text output", async () => {
38
39
  await withDir(async (dir) => {
39
40
  await writeFile(join(dir, "f.txt"), "line1\nline2\n");
40
- const r = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "f.txt" });
41
- const text = r.content[0];
42
- assert.equal(text.type, "text");
43
- assert.match(text.text, /1#[0-9A-Z]+│line1/);
44
- assert.match(text.text, /2#[0-9A-Z]+│line2/);
45
- assert.match(text.text, /f\.txt · 2 lines/);
41
+ const tool = makeReadOverride(dir, DEFAULT_CONFIG);
42
+ const formatter = createAnchorFormatter(DEFAULT_CONFIG.hashLen);
43
+ for (const options of [{}, { anchors: true }, { anchors: null }]) {
44
+ const result = await callTool(tool, { path: "f.txt", ...options });
45
+ assert.equal(result.isError, undefined);
46
+ assert.equal(result.content[0].type, "text");
47
+ assert.equal(
48
+ result.content[0].text,
49
+ ["f.txt · 2 lines", formatter.row(1, "line1"), formatter.row(2, "line2")].join("\n"),
50
+ );
51
+ }
46
52
  });
47
53
  });
48
54
 
55
+ test("read without anchors → preserves the header and raw window with LF and visible standalone CR", async () =>
56
+ withDir(async (dir) => {
57
+ const tool = makeReadOverride(dir, DEFAULT_CONFIG);
58
+ const lines = ["first", "second␍third", "", "12#ABCD│literal"];
59
+ for (const ending of ["\r\n", ""]) {
60
+ await writeFile(
61
+ join(dir, "raw.txt"),
62
+ `first\r\nsecond\rthird\r\n\r\n12#ABCD│literal${ending}`,
63
+ );
64
+ for (const [offset, limit] of [
65
+ [undefined, undefined],
66
+ [2, 2],
67
+ [2, 3],
68
+ ] as const) {
69
+ const start = offset ?? 1;
70
+ const result = await callTool(tool, { path: "raw.txt", anchors: false, offset, limit });
71
+ assert.equal(result.isError, undefined);
72
+ assert.equal(result.content[0].type, "text");
73
+ const header = `raw.txt · 4 lines${start > 1 ? ` (from line ${start})` : ""}${ending ? "" : " · no trailing newline"}`;
74
+ assert.equal(
75
+ result.content[0].text,
76
+ `${header}\n${lines.slice(start - 1, limit === undefined ? undefined : start - 1 + limit).join("\n")}`,
77
+ );
78
+ const report = reportOf(result, "read");
79
+ assert.equal(report?.nextOffset, undefined);
80
+ assert.equal(report?.outputLimit, undefined);
81
+ assert.equal(report?.lineTooLong, undefined);
82
+ }
83
+ }
84
+ }));
85
+
86
+ test("read without anchors at the same byte cap → fits more complete rows and retains byte-limit pagination", async () =>
87
+ withDir(async (dir) => {
88
+ const budget = outputBudgetsFor(2_048);
89
+ const tool = makeReadOverride(dir, DEFAULT_CONFIG, () => budget);
90
+ const visibleLine = "界␍x";
91
+ const rowCount = Math.floor((budget.readBytes + 1) / (Buffer.byteLength(visibleLine) + 1));
92
+ const totalLines = rowCount + 2;
93
+ await writeFile(join(dir, "raw.txt"), Array(totalLines).fill("界\rx").join("\r\n"));
94
+ const anchored = await callTool(tool, { path: "raw.txt", limit: totalLines });
95
+ const raw = await callTool(tool, { path: "raw.txt", limit: totalLines, anchors: false });
96
+ assert.equal(raw.isError, undefined);
97
+ assert.equal(raw.content[0].type, "text");
98
+ assert.equal(
99
+ raw.content[0].text,
100
+ `raw.txt · ${totalLines} lines · no trailing newline\n${Array(rowCount).fill(visibleLine).join("\n")}`,
101
+ );
102
+ const report = reportOf(raw, "read");
103
+ const anchoredReport = reportOf(anchored, "read");
104
+ assert.equal(report?.nextOffset, rowCount + 1);
105
+ assert.ok(anchoredReport?.nextOffset);
106
+ assert.ok(rowCount + 1 > anchoredReport.nextOffset);
107
+ for (const facts of [report, anchoredReport]) {
108
+ assert.equal(facts?.outputLimit, formatByteSize(budget.readBytes));
109
+ assert.equal(facts?.lineTooLong, undefined);
110
+ }
111
+ const next = await callTool(tool, {
112
+ path: "raw.txt",
113
+ anchors: false,
114
+ offset: report.nextOffset,
115
+ });
116
+ assert.equal(next.content[0].type, "text");
117
+ assert.equal(
118
+ next.content[0].text,
119
+ `raw.txt · ${totalLines} lines (from line ${rowCount + 1}) · no trailing newline\n${visibleLine}\n${visibleLine}`,
120
+ );
121
+ assert.equal(reportOf(next, "read")?.nextOffset, undefined);
122
+ assert.equal(reportOf(next, "read")?.outputLimit, undefined);
123
+ }));
124
+
125
+ test("read without anchors first row at or beyond the byte cap → counts UTF-8 content without a prefix", async () =>
126
+ withDir(async (dir) => {
127
+ const budget = outputBudgetsFor(2_048);
128
+ const tool = makeReadOverride(dir, DEFAULT_CONFIG, () => budget);
129
+ const content = "界".repeat(Math.floor(budget.readBytes / Buffer.byteLength("界")));
130
+ const fitting = content + "x".repeat(budget.readBytes - Buffer.byteLength(content));
131
+ for (const [source, fits] of [
132
+ [fitting, true],
133
+ [fitting + "x", false],
134
+ ["\r".repeat(Math.floor(budget.readBytes / Buffer.byteLength("␍")) + 1), false],
135
+ ] as const) {
136
+ await writeFile(join(dir, "raw.txt"), source);
137
+ const result = await callTool(tool, { path: "raw.txt", anchors: false });
138
+ assert.equal(result.isError, undefined);
139
+ assert.equal(result.content[0].type, "text");
140
+ assert.equal(
141
+ result.content[0].text,
142
+ `raw.txt · 1 lines · no trailing newline\n${fits ? source : ""}`,
143
+ );
144
+ const report = reportOf(result, "read");
145
+ assert.equal(report?.lineTooLong, fits ? undefined : formatByteSize(budget.readBytes));
146
+ assert.equal(report?.outputLimit, undefined);
147
+ assert.equal(report?.nextOffset, undefined);
148
+ }
149
+ }));
150
+
49
151
  test("absolute path inside cwd → read header uses relative spelling", async () =>
50
152
  withDir(async (dir) => {
51
153
  const path = join(dir, "f.txt");
@@ -75,6 +177,53 @@ test(
75
177
  }),
76
178
  );
77
179
 
180
+ test("read supported PNG → exposes the native image schema and structured image", async () =>
181
+ withDir(async (dir) => {
182
+ await writeFile(
183
+ join(dir, "image.png"),
184
+ Buffer.from(
185
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=",
186
+ "base64",
187
+ ),
188
+ );
189
+ const tool = makeReadOverride(dir, DEFAULT_CONFIG);
190
+ const result = await callTool(tool, { path: "image.png" });
191
+ assert.equal(result.isError, undefined);
192
+ const image = result.content.find((block) => block.type === "image");
193
+ assert.ok(image, JSON.stringify(result.content));
194
+ assert.equal(image.mimeType, "image/png");
195
+ assert.ok(image.data.length > 0);
196
+ assert.deepEqual(result.structuredContent, {
197
+ type: "image",
198
+ data: image.data,
199
+ mimeType: image.mimeType,
200
+ note: result.content.find((block) => block.type === "text")?.text,
201
+ });
202
+ const nativeSchema = createReadToolDefinition(dir).outputSchema;
203
+ assert.ok(nativeSchema);
204
+ assert.deepEqual(tool.outputSchema, nativeSchema);
205
+ }));
206
+
207
+ test("read UTF-8 text with or without continuation → structured text includes every text block", async () =>
208
+ withDir(async (dir) => {
209
+ await writeFile(join(dir, "text.txt"), "第一行\r\nsecond\r\n");
210
+ const tool = makeReadOverride(dir, {
211
+ ...DEFAULT_CONFIG,
212
+ read: { ...DEFAULT_CONFIG.read, defaultLimit: 1 },
213
+ });
214
+ for (const limit of [undefined, 2]) {
215
+ const result = await callTool(tool, { path: "text.txt", limit });
216
+ assert.equal(result.isError, undefined);
217
+ const textBlocks = result.content.flatMap((block) =>
218
+ block.type === "text" ? [block.text] : [],
219
+ );
220
+ assert.equal(textBlocks.length, limit === undefined ? 2 : 1);
221
+ assert.equal(reportOf(result, "read")?.nextOffset, limit === undefined ? 2 : undefined);
222
+ assert.equal(typeof result.structuredContent, "string");
223
+ assert.equal(result.structuredContent, textBlocks.join("\n"));
224
+ }
225
+ }));
226
+
78
227
  test("read execute: Pi-supported images without NUL bypass text decoding", async () =>
79
228
  withDir(async (dir) => {
80
229
  for (const [name, bytes, mime] of [
@@ -88,6 +237,56 @@ test("read execute: Pi-supported images without NUL bypass text decoding", async
88
237
  }
89
238
  }));
90
239
 
240
+ test("missing canonical read path with a native filename variant → reports the missing target", async () =>
241
+ withDir(async (dir) => {
242
+ await writeFile(join(dir, "shot 9\u202fAM.txt"), "variant must not be read\n");
243
+ const result = await callTool(makeReadOverride(dir, DEFAULT_CONFIG), { path: "shot 9 AM.txt" });
244
+ assert.equal(result.isError, true);
245
+ const report = reportOf(result, "read");
246
+ assert.equal(report?.error, "PATH_NOT_FOUND");
247
+ assert.deepEqual(report?.missing, [join(dir, "shot 9 AM.txt")]);
248
+ }));
249
+
250
+ test("file URLs escape special filenames → text and delegated reads open the exact file", async (t) => {
251
+ await withDir(async (dir) => {
252
+ const tool = makeReadOverride(dir, DEFAULT_CONFIG);
253
+ const cases = [
254
+ { name: "text.txt", bytes: Buffer.from("first\nsecond\n"), native: false },
255
+ { name: "binary.bin", bytes: Buffer.from("first\0\nsecond\n"), native: true },
256
+ {
257
+ name: "image.gif",
258
+ bytes: Buffer.from("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7", "base64"),
259
+ native: true,
260
+ },
261
+ ];
262
+ for (const { name, bytes, native } of cases) {
263
+ await t.test(name, async () => {
264
+ const path = join(dir, `space\u202Fname #% ${name}`);
265
+ await writeFile(path, bytes);
266
+ const result = await callTool(tool, { path: pathToFileURL(path).href });
267
+ assert.equal(result.isError, undefined);
268
+ assert.equal(result.details?.nativeRead === true, native);
269
+ if (name === "image.gif") {
270
+ assert.ok(result.content.some((block) => block.type === "image"));
271
+ } else {
272
+ const text = result.content.find((block) => block.type === "text")?.text;
273
+ assert.ok(text);
274
+ assert.ok(text.includes(native ? "first\0" : "│first"));
275
+ assert.ok(text.includes("second"));
276
+ if (!native) {
277
+ const header = text.split("\n")[0];
278
+ const returnedPath = header.slice(0, header.lastIndexOf(" · "));
279
+ const reread = await callTool(tool, { path: returnedPath });
280
+ assert.equal(reread.isError, undefined);
281
+ assert.deepEqual(reread.content, result.content);
282
+ }
283
+ }
284
+ assert.deepEqual(await readFile(path), bytes);
285
+ });
286
+ }
287
+ });
288
+ });
289
+
91
290
  test("read execute: a missing final newline is stated in the header", async () => {
92
291
  await withDir(async (dir) => {
93
292
  await writeFile(join(dir, "f.txt"), "line1\nline2");
@@ -126,7 +325,7 @@ test("read byte truncation counts UTF-8 and separators without cutting anchors",
126
325
  const maxBytes = DEFAULT_READ_MAX_BYTES;
127
326
  const hashLen = DEFAULT_CONFIG.hashLen;
128
327
  const prefixBytes = Buffer.byteLength(`1#${"X".repeat(hashLen)}│`);
129
- const first = "界".repeat(40000);
328
+ const first = "界".repeat(Math.floor(maxBytes / (2 * Buffer.byteLength("界"))));
130
329
  const second = "x".repeat(maxBytes - Buffer.byteLength(first) - 2 * prefixBytes);
131
330
  await writeFile(join(dir, "large.txt"), `${first}\n${second}\n`);
132
331
  const result = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "large.txt" });
@@ -275,13 +474,17 @@ test("read schema rejects empty paths and unknown fields before file access", as
275
474
 
276
475
  test("read byte truncation retains its budget and a continuation after complete returned rows", async () =>
277
476
  withDir(async (dir) => {
278
- await writeFile(join(dir, "large.txt"), `first\n${"x".repeat(DEFAULT_READ_MAX_BYTES)}\ntail\n`);
279
- const result = await call(makeReadOverride(dir, DEFAULT_CONFIG), {
280
- path: "large.txt",
281
- limit: 2,
282
- });
283
- assert.equal(reportOf(result, "read")?.nextOffset, 2);
284
- assert.equal(reportOf(result, "read")?.outputLimit, formatByteSize(DEFAULT_READ_MAX_BYTES));
477
+ const first = "x".repeat(Math.floor(DEFAULT_READ_MAX_BYTES / 2));
478
+ await writeFile(join(dir, "large.txt"), `skip\n${first}\n${first}y\ntail\n`);
479
+ const tool = makeReadOverride(dir, DEFAULT_CONFIG);
480
+ const result = await call(tool, { path: "large.txt", offset: 2, limit: 2 });
481
+ const report = reportOf(result, "read");
482
+ assert.equal(report?.nextOffset, 3);
483
+ assert.equal(report.outputLimit, formatByteSize(DEFAULT_READ_MAX_BYTES));
484
+ assert.match(result.content[0].text, /^2#[0-9A-Z]+│x+$/m);
485
+ const resumed = await call(tool, { path: "large.txt", offset: report.nextOffset, limit: 1 });
486
+ assert.match(resumed.content[0].text, /^3#[0-9A-Z]+│x+y$/m);
487
+ assert.equal(reportOf(resumed, "read")?.nextOffset, undefined);
285
488
  assert.match(reportOf(result, "read")?.next ?? "", /offset.*nextOffset/);
286
489
  assert.doesNotMatch(result.content[0].text, /showing lines|to continue/);
287
490
  }));
@@ -382,6 +585,10 @@ test("Unicode line separators in a read path or middle row → renders every fol
382
585
  lastComponent: undefined,
383
586
  invalidate() {},
384
587
  executionStarted: true,
588
+ durationMs: undefined,
589
+ outputPad: 1,
590
+ keyText: () => "",
591
+ keyHint: (_key, description) => description,
385
592
  argsComplete: true,
386
593
  isPartial: false,
387
594
  expanded: true,
@@ -399,3 +606,130 @@ test("Unicode line separators in a read path or middle row → renders every fol
399
606
  }
400
607
  }
401
608
  });
609
+
610
+ test("raw read rendering with an offset → numbers every source line from the header without parsing its content", async () =>
611
+ withDir(async (dir) => {
612
+ const tool = makeReadOverride(dir, DEFAULT_CONFIG);
613
+ const render = tool.renderResult;
614
+ assert.ok(render);
615
+ const lines = ["12#ABCD│literal", "", "before\u2028middle\u2029after", "last"];
616
+ await writeFile(join(dir, "raw.txt"), lines.join("\n"));
617
+ for (const offset of [1, 2]) {
618
+ const args = { path: "raw.txt", anchors: false, offset };
619
+ const result = await callTool(tool, args);
620
+ const rendered: string[] = render(
621
+ JSON.parse(JSON.stringify(result)),
622
+ { expanded: true, isPartial: false },
623
+ stubTheme,
624
+ {
625
+ args,
626
+ state: {},
627
+ cwd: dir,
628
+ toolCallId: "raw-read",
629
+ lastComponent: undefined,
630
+ invalidate() {},
631
+ executionStarted: true,
632
+ durationMs: undefined,
633
+ outputPad: 1,
634
+ keyText: () => "",
635
+ keyHint: (_key, description) => description,
636
+ argsComplete: true,
637
+ isPartial: false,
638
+ expanded: true,
639
+ showImages: false,
640
+ isError: false,
641
+ },
642
+ )
643
+ .render(120)
644
+ .map((line) => line.trimEnd());
645
+ assert.deepEqual(rendered, [
646
+ `raw.txt · 4 lines${offset > 1 ? ` (from line ${offset})` : ""} · no trailing newline`,
647
+ ...lines
648
+ .slice(offset - 1)
649
+ .map((line, index) => ` ${offset + index}:${line ? ` ${line}` : ""}`),
650
+ ]);
651
+ }
652
+ }));
653
+
654
+ test("unanchored read with no rows or a real empty row → expanded rendering preserves the selected rows", async (t) =>
655
+ withDir(async (dir) => {
656
+ const budget = outputBudgetsFor(4_000);
657
+ const tool = makeReadOverride(dir, DEFAULT_CONFIG, () => budget);
658
+ const render = tool.renderResult;
659
+ assert.ok(render);
660
+ const cases = [
661
+ { name: "empty file", path: "empty.txt", content: "", header: "empty.txt · 0 lines" },
662
+ {
663
+ name: "offset past EOF",
664
+ path: "blank.txt",
665
+ content: "a\n\nb\n",
666
+ offset: 9,
667
+ header: "blank.txt · 3 lines (from line 9)",
668
+ },
669
+ {
670
+ name: "first line exceeds the byte budget",
671
+ path: "long.txt",
672
+ content: "x".repeat(budget.readBytes + 1) + "\n",
673
+ header: "long.txt · 1 lines",
674
+ lineTooLong: true,
675
+ },
676
+ {
677
+ name: "real empty row",
678
+ path: "blank.txt",
679
+ content: "a\n\nb\n",
680
+ offset: 2,
681
+ limit: 1,
682
+ header: "blank.txt · 3 lines (from line 2)",
683
+ emptyRow: true,
684
+ },
685
+ ];
686
+ for (const c of cases) {
687
+ await t.test(c.name, async () => {
688
+ await writeFile(join(dir, c.path), c.content);
689
+ const args = { path: c.path, anchors: false, offset: c.offset, limit: c.limit };
690
+ const result = await callTool(tool, args);
691
+ assert.equal(result.isError, undefined);
692
+ const rendered = render(
693
+ JSON.parse(JSON.stringify(result)),
694
+ { expanded: true, isPartial: false },
695
+ stubTheme,
696
+ {
697
+ args,
698
+ state: {},
699
+ cwd: dir,
700
+ toolCallId: "raw-read",
701
+ lastComponent: undefined,
702
+ invalidate() {},
703
+ executionStarted: true,
704
+ durationMs: undefined,
705
+ outputPad: 1,
706
+ keyText: () => "",
707
+ keyHint: (_key, description) => description,
708
+ argsComplete: true,
709
+ isPartial: false,
710
+ expanded: true,
711
+ showImages: false,
712
+ isError: false,
713
+ },
714
+ ).render(120);
715
+ assert.equal(rendered[0].trimEnd(), c.header);
716
+ const codeRows = rendered.slice(1).filter((line) => /^\s+\d+: /.test(line));
717
+ if (c.emptyRow) {
718
+ assert.equal(codeRows.length, 1);
719
+ assert.ok(codeRows[0].startsWith(" 2: "));
720
+ assert.equal(codeRows[0].trimEnd(), " 2:");
721
+ } else {
722
+ assert.deepEqual(codeRows, []);
723
+ }
724
+ if (c.lineTooLong) {
725
+ assert.equal(reportOf(result, "read")?.lineTooLong, formatByteSize(budget.readBytes));
726
+ assert.ok(
727
+ rendered.some((line) =>
728
+ line.includes(`lineTooLong: ${formatByteSize(budget.readBytes)}`),
729
+ ),
730
+ );
731
+ assert.ok(rendered.some((line) => line.includes("next: ")));
732
+ }
733
+ });
734
+ }
735
+ }));
@@ -0,0 +1,42 @@
1
+ import assert from "node:assert/strict";
2
+ import { spawnSync } from "node:child_process";
3
+ import { test } from "node:test";
4
+ import { pathToFileURL } from "node:url";
5
+ import { resolve } from "node:path";
6
+
7
+ const workerModule = pathToFileURL(resolve("src/pi/regex-worker.ts")).href;
8
+ const grepEntry = pathToFileURL(resolve("src/pi/grep-worker.mjs")).href;
9
+ const replaceEntry = pathToFileURL(resolve("src/pi/replace-worker.mjs")).href;
10
+
11
+ test("input-type inherited from eval → both file workers run with other flags preserved", () => {
12
+ const script = `
13
+ (async () => {
14
+ const { default: assert } = await import('node:assert/strict');
15
+ const { withRegexWorker } = await import(${JSON.stringify(workerModule)});
16
+ const run = (entry, input) => withRegexWorker(new URL(entry), value => value, 10000, undefined, send => send(input));
17
+ const probe = new URL('data:text/javascript,' + encodeURIComponent("import { parentPort } from 'node:worker_threads'; parentPort.on('message', () => parentPort.postMessage({ result: process.execArgv }));"));
18
+ const flags = await run(probe.href, {});
19
+ assert.ok(flags.includes('--no-warnings'));
20
+ assert.deepEqual(flags, process.execArgv);
21
+ const search = await run(${JSON.stringify(grepEntry)}, { source: 'safe', query: { patterns: ['safe'], literal: false, ignoreCase: false, multiline: false }, limit: 10 });
22
+ assert.equal(search.lines.length, 1);
23
+ const replacement = await run(${JSON.stringify(replaceEntry)}, { source: 'safe', rules: [{ find: 'safe', replace: 'changed', literal: false }] });
24
+ assert.equal(replacement.text, 'changed');
25
+ })().catch(error => { console.error(error); process.exitCode = 1; });
26
+ `;
27
+ for (const flags of [
28
+ ["--input-type=module"],
29
+ ["--input-type", "module"],
30
+ ["--input-type=commonjs"],
31
+ ["--input-type", "commonjs"],
32
+ ["--use-largepages=off"],
33
+ ["--use-largepages=off", "--input-type=module"],
34
+ ["--use-largepages=off", "--input-type=commonjs"],
35
+ ]) {
36
+ const result = spawnSync(process.execPath, [...flags, "--no-warnings", "--eval", script], {
37
+ encoding: "utf8",
38
+ timeout: 30000,
39
+ });
40
+ assert.equal(result.status, 0, `${flags.join(" ")}: ${result.stderr}`);
41
+ }
42
+ });
@@ -17,10 +17,16 @@ export async function withRegexWorker<Input, Result, Output>(
17
17
  resourceLimits?: ResourceLimits,
18
18
  ): Promise<Output> {
19
19
  throwIfCancelled(signal);
20
- const worker = new Worker(entry, { resourceLimits });
20
+ // A data URL accepts inherited --input-type while the imported file retains its own module type.
21
+ const bootstrap = new URL(
22
+ `data:text/javascript,${encodeURIComponent(`import ${JSON.stringify(entry.href)};`)}`,
23
+ );
24
+ const worker = new Worker(bootstrap, { resourceLimits });
21
25
  let failure: Error | undefined;
22
26
  let pending: { resolve: (result: Result) => void; reject: (error: Error) => void } | undefined;
23
27
  let timer: ReturnType<typeof setTimeout> | undefined;
28
+ let termination: ReturnType<Worker["terminate"]> | undefined;
29
+ const terminate = () => (termination ??= worker.terminate());
24
30
  const clear = () => {
25
31
  clearTimeout(timer);
26
32
  const previous = pending;
@@ -64,15 +70,15 @@ export async function withRegexWorker<Input, Result, Output>(
64
70
  if (failure) throw failure;
65
71
  return new Promise<Result>((resolve, reject) => {
66
72
  pending = { resolve, reject };
67
- timer = setTimeout(
68
- () =>
69
- fail(
70
- new HashlineError("REGEX_TIMEOUT", "Regex evaluation timed out.", {
71
- facts: { timeoutMs },
72
- }),
73
- ),
74
- timeoutMs,
75
- );
73
+ timer = setTimeout(() => {
74
+ fail(
75
+ new HashlineError("REGEX_TIMEOUT", "Regex evaluation timed out.", {
76
+ facts: { timeoutMs },
77
+ }),
78
+ );
79
+ // A grep caller may still be scanning for NUL after evaluation times out.
80
+ void terminate();
81
+ }, timeoutMs);
76
82
  worker.postMessage(input);
77
83
  });
78
84
  });
@@ -81,6 +87,6 @@ export async function withRegexWorker<Input, Result, Output>(
81
87
  } finally {
82
88
  clear();
83
89
  signal?.removeEventListener("abort", abort);
84
- await worker.terminate();
90
+ await terminate();
85
91
  }
86
92
  }