@criogaid/pi-hashline-edit 0.12.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 (88) hide show
  1. package/LICENSE +1 -0
  2. package/README.md +59 -16
  3. package/README.zh-CN.md +59 -16
  4. package/package.json +2 -2
  5. package/src/core/AGENTS.md +2 -2
  6. package/src/core/apply.test.ts +13 -0
  7. package/src/core/apply.ts +5 -9
  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 -36
  13. package/src/core/search-analysis.test.ts +66 -61
  14. package/src/core/search-analysis.ts +24 -39
  15. package/src/core/search-matrix.test.ts +2 -2
  16. package/src/core/search-matrix.testing.ts +6 -16
  17. package/src/core/search-schema.ts +0 -1
  18. package/src/core/search.test.ts +6 -19
  19. package/src/core/search.ts +10 -8
  20. package/src/index.ts +27 -2
  21. package/src/integration/config-registration.test.ts +77 -4
  22. package/src/integration/fusion-dispatch.test.ts +47 -2
  23. package/src/integration/grep-errors.test.ts +31 -0
  24. package/src/integration/grep-flags.test.ts +13 -196
  25. package/src/integration/grep-js-completeness.test.ts +41 -8
  26. package/src/integration/grep-line-candidates.test.ts +3 -33
  27. package/src/integration/grep-matrix.test.ts +1 -1
  28. package/src/integration/grep-path-matrix.test.ts +59 -65
  29. package/src/integration/grep-prefilter-coverage.test.ts +15 -8
  30. package/src/integration/grep-process-limits.test.ts +46 -0
  31. package/src/integration/grep-regex.test.ts +7 -2
  32. package/src/integration/grep-rg.test.ts +63 -12
  33. package/src/integration/grep-translation.test.ts +14 -7
  34. package/src/integration/model-budget-lifecycle.test.ts +41 -2
  35. package/src/integration/npm-package.testing.ts +2 -3
  36. package/src/integration/replace-package.testing.ts +2 -2
  37. package/src/pi/AGENTS.md +21 -13
  38. package/src/pi/action-fusion.test.ts +38 -4
  39. package/src/pi/action-fusion.ts +23 -19
  40. package/src/pi/argument-diagnostics.ts +28 -48
  41. package/src/pi/argument-validation.test.ts +61 -27
  42. package/src/pi/argument-validation.ts +34 -0
  43. package/src/pi/budgets.ts +19 -10
  44. package/src/pi/config.test.ts +1 -1
  45. package/src/pi/diagnostic-buffer.test.ts +1 -0
  46. package/src/pi/edit-tool.ts +1 -1
  47. package/src/pi/failure-context.test.ts +23 -2
  48. package/src/pi/failure-context.ts +36 -42
  49. package/src/pi/failure-path.test.ts +8 -3
  50. package/src/pi/file-commit.test.ts +109 -52
  51. package/src/pi/file-commit.ts +62 -56
  52. package/src/pi/fusion-card.ts +3 -2
  53. package/src/pi/grep-candidates.test.ts +5 -5
  54. package/src/pi/grep-candidates.ts +81 -50
  55. package/src/pi/grep-matrix.test.ts +14 -29
  56. package/src/pi/grep-order.test.ts +132 -9
  57. package/src/pi/grep-output.ts +169 -51
  58. package/src/pi/grep-render.ts +40 -34
  59. package/src/pi/grep-rg.testing.ts +9 -6
  60. package/src/pi/grep-scope.ts +51 -29
  61. package/src/pi/grep-search.ts +96 -71
  62. package/src/pi/grep-tool.ts +13 -22
  63. package/src/pi/grep.test.ts +310 -84
  64. package/src/pi/model-budgets.test.ts +56 -6
  65. package/src/pi/model-budgets.ts +7 -4
  66. package/src/pi/mutation-result.test.ts +25 -1
  67. package/src/pi/mutation-result.ts +7 -2
  68. package/src/pi/mutation-runner.ts +3 -4
  69. package/src/pi/output-budgets.test.ts +3 -1
  70. package/src/pi/path.ts +18 -4
  71. package/src/pi/pi.test.ts +22 -0
  72. package/src/pi/read-delegation.test.ts +119 -0
  73. package/src/pi/read-tool.ts +109 -61
  74. package/src/pi/read.test.ts +306 -17
  75. package/src/pi/regex-worker.test.ts +42 -0
  76. package/src/pi/regex-worker.ts +17 -11
  77. package/src/pi/registration.test.ts +157 -102
  78. package/src/pi/render.test.ts +54 -0
  79. package/src/pi/render.ts +9 -9
  80. package/src/pi/replace-tool.ts +5 -2
  81. package/src/pi/report-schema.ts +52 -31
  82. package/src/pi/report.test.ts +60 -10
  83. package/src/pi/rg-process.ts +41 -5
  84. package/src/pi/rg-regex.test.ts +12 -52
  85. package/src/pi/rg-regex.ts +29 -77
  86. package/src/pi/text-stream.test.ts +3 -0
  87. package/src/pi/text-stream.ts +1 -1
  88. package/src/testing/regex-translation-corpus.ts +39 -96
@@ -5,14 +5,14 @@ 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
7
  import { pathToFileURL } from "node:url";
8
- import { initTheme } from "@earendil-works/pi-coding-agent";
8
+ import { createReadToolDefinition, initTheme } from "@earendil-works/pi-coding-agent";
9
9
  import type { Theme } from "@earendil-works/pi-coding-agent";
10
10
  import { validateToolArguments } from "@earendil-works/pi-ai";
11
11
  import { makeReadOverride } from "./tool-factories.testing.ts";
12
12
  import { computeLineHash } from "../core/hash.ts";
13
13
  import { callTool } from "./tool-call.testing.ts";
14
14
  import { DEFAULT_CONFIG } from "./tool-factories.testing.ts";
15
- import { formatByteSize } from "./budgets.ts";
15
+ import { formatByteSize, outputBudgetsFor } from "./budgets.ts";
16
16
  import { DEFAULT_OUTPUT_BUDGETS } from "./tool-factories.testing.ts";
17
17
  import { reportOf } from "./report.ts";
18
18
  import { createAnchorFormatter } from "./anchor-format.ts";
@@ -35,18 +35,119 @@ const stubTheme = { fg: (_k: string, s: string) => s, bold: (s: string) => s } a
35
35
 
36
36
  initTheme();
37
37
 
38
- test("read execute: text outputs LINE#HASH│content", async () => {
38
+ test("read anchors omitted, true, or null → preserves anchored text output", async () => {
39
39
  await withDir(async (dir) => {
40
40
  await writeFile(join(dir, "f.txt"), "line1\nline2\n");
41
- const r = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "f.txt" });
42
- const text = r.content[0];
43
- assert.equal(text.type, "text");
44
- assert.match(text.text, /1#[0-9A-Z]+│line1/);
45
- assert.match(text.text, /2#[0-9A-Z]+│line2/);
46
- 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
+ }
47
52
  });
48
53
  });
49
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
+
50
151
  test("absolute path inside cwd → read header uses relative spelling", async () =>
51
152
  withDir(async (dir) => {
52
153
  const path = join(dir, "f.txt");
@@ -76,6 +177,53 @@ test(
76
177
  }),
77
178
  );
78
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
+
79
227
  test("read execute: Pi-supported images without NUL bypass text decoding", async () =>
80
228
  withDir(async (dir) => {
81
229
  for (const [name, bytes, mime] of [
@@ -89,6 +237,16 @@ test("read execute: Pi-supported images without NUL bypass text decoding", async
89
237
  }
90
238
  }));
91
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
+
92
250
  test("file URLs escape special filenames → text and delegated reads open the exact file", async (t) => {
93
251
  await withDir(async (dir) => {
94
252
  const tool = makeReadOverride(dir, DEFAULT_CONFIG);
@@ -167,7 +325,7 @@ test("read byte truncation counts UTF-8 and separators without cutting anchors",
167
325
  const maxBytes = DEFAULT_READ_MAX_BYTES;
168
326
  const hashLen = DEFAULT_CONFIG.hashLen;
169
327
  const prefixBytes = Buffer.byteLength(`1#${"X".repeat(hashLen)}│`);
170
- const first = "界".repeat(40000);
328
+ const first = "界".repeat(Math.floor(maxBytes / (2 * Buffer.byteLength("界"))));
171
329
  const second = "x".repeat(maxBytes - Buffer.byteLength(first) - 2 * prefixBytes);
172
330
  await writeFile(join(dir, "large.txt"), `${first}\n${second}\n`);
173
331
  const result = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "large.txt" });
@@ -316,13 +474,17 @@ test("read schema rejects empty paths and unknown fields before file access", as
316
474
 
317
475
  test("read byte truncation retains its budget and a continuation after complete returned rows", async () =>
318
476
  withDir(async (dir) => {
319
- await writeFile(join(dir, "large.txt"), `first\n${"x".repeat(DEFAULT_READ_MAX_BYTES)}\ntail\n`);
320
- const result = await call(makeReadOverride(dir, DEFAULT_CONFIG), {
321
- path: "large.txt",
322
- limit: 2,
323
- });
324
- assert.equal(reportOf(result, "read")?.nextOffset, 2);
325
- 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);
326
488
  assert.match(reportOf(result, "read")?.next ?? "", /offset.*nextOffset/);
327
489
  assert.doesNotMatch(result.content[0].text, /showing lines|to continue/);
328
490
  }));
@@ -444,3 +606,130 @@ test("Unicode line separators in a read path or middle row → renders every fol
444
606
  }
445
607
  }
446
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
  }