@criogaid/pi-hashline-edit 0.13.0 → 0.15.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 (152) hide show
  1. package/README.md +18 -12
  2. package/README.zh-CN.md +18 -12
  3. package/package.json +8 -1
  4. package/src/core/AGENTS.md +3 -1
  5. package/src/core/apply.ts +110 -117
  6. package/src/core/character-set.ts +2 -3
  7. package/src/core/copy-span.ts +15 -0
  8. package/src/core/errors.ts +24 -9
  9. package/src/core/lines.ts +71 -17
  10. package/src/core/ranges.ts +5 -4
  11. package/src/core/replace-schema.ts +3 -1
  12. package/src/core/replace.ts +50 -29
  13. package/src/core/search-analysis.ts +21 -22
  14. package/src/core/search.ts +15 -32
  15. package/src/core/types.ts +3 -0
  16. package/src/index.ts +47 -39
  17. package/src/pi/AGENTS.md +30 -19
  18. package/src/pi/action-fusion.ts +284 -211
  19. package/src/pi/argument-diagnostics.ts +50 -37
  20. package/src/pi/argument-error.ts +2 -2
  21. package/src/pi/argument-validation.ts +163 -66
  22. package/src/pi/budgets.ts +12 -0
  23. package/src/pi/diagnostic-buffer.ts +12 -11
  24. package/src/pi/edit-tool.ts +138 -115
  25. package/src/pi/error-text.ts +10 -2
  26. package/src/pi/failure-context.ts +24 -37
  27. package/src/pi/file-commit.ts +131 -164
  28. package/src/pi/file-read.ts +122 -31
  29. package/src/pi/fusion-arguments.ts +214 -0
  30. package/src/pi/fusion-card.ts +102 -60
  31. package/src/pi/grep-candidates.ts +35 -22
  32. package/src/pi/grep-output.ts +197 -190
  33. package/src/pi/grep-render.ts +22 -13
  34. package/src/pi/grep-reread.ts +7 -6
  35. package/src/pi/grep-scope.ts +31 -16
  36. package/src/pi/grep-search.ts +56 -47
  37. package/src/pi/grep-tool.ts +35 -33
  38. package/src/pi/grep-worker.ts +3 -4
  39. package/src/pi/mutation-diff.ts +238 -0
  40. package/src/pi/mutation-result.ts +102 -79
  41. package/src/pi/mutation-runner.ts +107 -84
  42. package/src/pi/native-bash.ts +41 -0
  43. package/src/pi/path.ts +59 -6
  44. package/src/pi/read-tool.ts +173 -138
  45. package/src/pi/regex-worker.ts +14 -8
  46. package/src/pi/render.ts +101 -54
  47. package/src/pi/replace-regex.ts +1 -1
  48. package/src/pi/replace-tool.ts +14 -7
  49. package/src/pi/report-cause.ts +34 -17
  50. package/src/pi/report-schema.ts +184 -85
  51. package/src/pi/report.ts +133 -64
  52. package/src/pi/rg-process.ts +68 -48
  53. package/src/pi/schema.ts +4 -0
  54. package/src/pi/text-stream.ts +81 -87
  55. package/src/pi/workspace-cwd.js +2 -0
  56. package/src/pi/workspace.ts +46 -0
  57. package/src/pi/write-tool.ts +19 -13
  58. package/src/core/apply.test.ts +0 -644
  59. package/src/core/case-fold.test.ts +0 -35
  60. package/src/core/character-set.test.ts +0 -97
  61. package/src/core/errors.test.ts +0 -39
  62. package/src/core/hash.test.ts +0 -64
  63. package/src/core/lines.test.ts +0 -63
  64. package/src/core/ranges.test.ts +0 -123
  65. package/src/core/replace.test.ts +0 -187
  66. package/src/core/search-analysis.test.ts +0 -210
  67. package/src/core/search-matrix.test.ts +0 -64
  68. package/src/core/search-matrix.testing.ts +0 -171
  69. package/src/core/search.test.ts +0 -132
  70. package/src/core/text.test.ts +0 -52
  71. package/src/integration/config-registration.test.ts +0 -291
  72. package/src/integration/fusion-dispatch.test.ts +0 -320
  73. package/src/integration/grep-errors.test.ts +0 -81
  74. package/src/integration/grep-flags.test.ts +0 -76
  75. package/src/integration/grep-js-completeness.test.ts +0 -278
  76. package/src/integration/grep-line-candidates.test.ts +0 -201
  77. package/src/integration/grep-matrix.test.ts +0 -118
  78. package/src/integration/grep-order.test.ts +0 -78
  79. package/src/integration/grep-path-matrix.test.ts +0 -128
  80. package/src/integration/grep-prefilter-coverage.test.ts +0 -204
  81. package/src/integration/grep-process-limits.test.ts +0 -122
  82. package/src/integration/grep-regex.test.ts +0 -412
  83. package/src/integration/grep-rg.test.ts +0 -1659
  84. package/src/integration/grep-scan-budget.test.ts +0 -111
  85. package/src/integration/grep-translation.test.ts +0 -199
  86. package/src/integration/large-text.test.ts +0 -70
  87. package/src/integration/model-budget-lifecycle.test.ts +0 -186
  88. package/src/integration/mutation-file-types.test.ts +0 -30
  89. package/src/integration/mutation-file-types.testing.ts +0 -33
  90. package/src/integration/npm-package.test.ts +0 -19
  91. package/src/integration/npm-package.testing.ts +0 -243
  92. package/src/integration/publication-read-changes.test.ts +0 -454
  93. package/src/integration/read-changes.test.ts +0 -98
  94. package/src/integration/replace-package.test.ts +0 -22
  95. package/src/integration/replace-package.testing.ts +0 -36
  96. package/src/integration/replace-worker-boundary.test.ts +0 -127
  97. package/src/integration/report-replay.test.ts +0 -91
  98. package/src/integration/utf8-errors.test.ts +0 -46
  99. package/src/pi/action-fusion.test.ts +0 -659
  100. package/src/pi/action-fusion.testing.ts +0 -38
  101. package/src/pi/anchor-format.test.ts +0 -124
  102. package/src/pi/argument-error.testing.ts +0 -46
  103. package/src/pi/argument-format.test.ts +0 -196
  104. package/src/pi/argument-validation.test.ts +0 -1007
  105. package/src/pi/codemode.test.ts +0 -101
  106. package/src/pi/config.test.ts +0 -204
  107. package/src/pi/diagnostic-buffer.test.ts +0 -115
  108. package/src/pi/directory-sync.test.ts +0 -57
  109. package/src/pi/execute.test.ts +0 -1257
  110. package/src/pi/extension-loading.test.ts +0 -14
  111. package/src/pi/extension-loading.testing.ts +0 -3
  112. package/src/pi/failure-context.test.ts +0 -370
  113. package/src/pi/failure-path.test.ts +0 -289
  114. package/src/pi/file-commit.test.ts +0 -628
  115. package/src/pi/file-read.test.ts +0 -29
  116. package/src/pi/file-snapshot.test.ts +0 -22
  117. package/src/pi/fusion-card-interaction.test.ts +0 -143
  118. package/src/pi/fusion-card.test.ts +0 -353
  119. package/src/pi/grep-candidates.test.ts +0 -26
  120. package/src/pi/grep-matrix.test.ts +0 -68
  121. package/src/pi/grep-order.test.ts +0 -447
  122. package/src/pi/grep-output.testing.ts +0 -24
  123. package/src/pi/grep-rg.testing.ts +0 -73
  124. package/src/pi/grep.test.ts +0 -1670
  125. package/src/pi/model-budgets.test.ts +0 -96
  126. package/src/pi/mutation-outcome.testing.ts +0 -20
  127. package/src/pi/mutation-result.test.ts +0 -96
  128. package/src/pi/output-budgets.test.ts +0 -221
  129. package/src/pi/pi.test.ts +0 -158
  130. package/src/pi/read-delegation.test.ts +0 -119
  131. package/src/pi/read.test.ts +0 -735
  132. package/src/pi/regex-worker.test.ts +0 -42
  133. package/src/pi/registration.test.ts +0 -549
  134. package/src/pi/render.test.ts +0 -841
  135. package/src/pi/replace.test.ts +0 -634
  136. package/src/pi/report-failure.testing.ts +0 -27
  137. package/src/pi/report.test.ts +0 -533
  138. package/src/pi/result-safety.test.ts +0 -597
  139. package/src/pi/rg-process.test.ts +0 -133
  140. package/src/pi/rg-regex.test.ts +0 -40
  141. package/src/pi/text-stream.test.ts +0 -281
  142. package/src/pi/tool-call.testing.ts +0 -61
  143. package/src/pi/tool-factories.testing.ts +0 -59
  144. package/src/pi/write.test.ts +0 -256
  145. package/src/testing/extension-loader.testing.ts +0 -24
  146. package/src/testing/installation.testing.ts +0 -77
  147. package/src/testing/process.testing.ts +0 -33
  148. package/src/testing/regex-host.testing.ts +0 -20
  149. package/src/testing/regex-translation-corpus.ts +0 -267
  150. package/src/testing/rg-line-listing.fixture.mjs +0 -7
  151. package/src/testing/run-tests.ts +0 -47
  152. package/src/testing/session.testing.ts +0 -127
@@ -1,735 +0,0 @@
1
- import { rejectsArgument, rejectsArguments } from "./argument-error.testing.ts";
2
- import { test } from "node:test";
3
- import assert from "node:assert/strict";
4
- import { mkdir, mkdtemp, rm, readFile, writeFile } from "node:fs/promises";
5
- import { tmpdir } from "node:os";
6
- import { join } from "node:path";
7
- import { pathToFileURL } from "node:url";
8
- import { createReadToolDefinition, initTheme } from "@earendil-works/pi-coding-agent";
9
- import type { Theme } from "@earendil-works/pi-coding-agent";
10
- import { validateToolArguments } from "@earendil-works/pi-ai";
11
- import { makeReadOverride } from "./tool-factories.testing.ts";
12
- import { computeLineHash } from "../core/hash.ts";
13
- import { callTool } from "./tool-call.testing.ts";
14
- import { DEFAULT_CONFIG } from "./tool-factories.testing.ts";
15
- import { formatByteSize, outputBudgetsFor } from "./budgets.ts";
16
- import { DEFAULT_OUTPUT_BUDGETS } from "./tool-factories.testing.ts";
17
- import { reportOf } from "./report.ts";
18
- import { createAnchorFormatter } from "./anchor-format.ts";
19
-
20
- const DEFAULT_READ_MAX_BYTES = DEFAULT_OUTPUT_BUDGETS.readBytes;
21
-
22
- async function withDir<T>(fn: (dir: string) => Promise<T>): Promise<T> {
23
- const dir = await mkdtemp(join(tmpdir(), "hl-"));
24
- try {
25
- return await fn(dir);
26
- } finally {
27
- await rm(dir, { recursive: true, force: true });
28
- }
29
- }
30
-
31
- /** Call a tool through Pi's argument preparation and schema validation, as production does. */
32
- const call = (tool: any, params: any) => callTool(tool, params, { toolCallId: "0" });
33
-
34
- const stubTheme = { fg: (_k: string, s: string) => s, bold: (s: string) => s } as Theme;
35
-
36
- initTheme();
37
-
38
- test("read anchors omitted, true, or null → preserves anchored text output", async () => {
39
- await withDir(async (dir) => {
40
- await writeFile(join(dir, "f.txt"), "line1\nline2\n");
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
- }
52
- });
53
- });
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
-
151
- test("absolute path inside cwd → read header uses relative spelling", async () =>
152
- withDir(async (dir) => {
153
- const path = join(dir, "f.txt");
154
- await writeFile(path, "line1\nline2\n");
155
- const result = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path });
156
- assert.equal(result.isError, undefined);
157
- assert.equal(result.content[0].text.split("\n")[0], "f.txt · 2 lines");
158
- }));
159
-
160
- test(
161
- "Windows absolute path outside cwd → read header uses forward slashes",
162
- {
163
- skip: process.platform !== "win32",
164
- },
165
- async () =>
166
- withDir(async (dir) => {
167
- const cwd = join(dir, "workspace");
168
- await mkdir(cwd);
169
- const path = join(dir, "outside.txt");
170
- await writeFile(path, "line1\nline2\n");
171
- const result = await call(makeReadOverride(cwd, DEFAULT_CONFIG), { path });
172
- assert.equal(result.isError, undefined);
173
- assert.equal(
174
- result.content[0].text.split("\n")[0],
175
- `${path.replaceAll("\\", "/")} · 2 lines`,
176
- );
177
- }),
178
- );
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
-
227
- test("read execute: Pi-supported images without NUL bypass text decoding", async () =>
228
- withDir(async (dir) => {
229
- for (const [name, bytes, mime] of [
230
- ["picture.jpg", Buffer.from([0xff, 0xd8, 0xff, 0xd9]), "image/jpeg"],
231
- ["picture.gif", Buffer.from("GIF89a"), "image/gif"],
232
- ] as const) {
233
- await writeFile(join(dir, name), bytes);
234
- const result: any = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: name });
235
- assert.ok(result.content[0].text.startsWith(`Read image file [${mime}]`));
236
- assert.deepEqual(await readFile(join(dir, name)), bytes);
237
- }
238
- }));
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
-
290
- test("read execute: a missing final newline is stated in the header", async () => {
291
- await withDir(async (dir) => {
292
- await writeFile(join(dir, "f.txt"), "line1\nline2");
293
- const bare: any = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "f.txt" });
294
- assert.match(bare.content[0].text, /f\.txt · 2 lines · no trailing newline/);
295
-
296
- await writeFile(join(dir, "g.txt"), "line1\nline2\n");
297
- const terminated: any = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "g.txt" });
298
- assert.doesNotMatch(terminated.content[0].text, /no trailing newline/);
299
- });
300
- });
301
-
302
- test("hash length stays 4 even for runs of identical lines (no explosion)", async () => {
303
- await withDir(async (dir) => {
304
- const f = join(dir, "f.txt");
305
- await writeFile(f, "\n\n\n\ncode\n");
306
- const r: any = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "f.txt" });
307
- const text: string = r.content[0].text;
308
- const rows = [...text.matchAll(/^(\d+)#([0-9A-Z]+)│(.*)$/gm)];
309
- assert.deepEqual(
310
- rows.map((row) => [Number(row[1]), row[3]]),
311
- [
312
- [1, ""],
313
- [2, ""],
314
- [3, ""],
315
- [4, ""],
316
- [5, "code"],
317
- ],
318
- );
319
- for (const row of rows) assert.equal(row[2].length, DEFAULT_CONFIG.hashLen);
320
- });
321
- });
322
-
323
- test("read byte truncation counts UTF-8 and separators without cutting anchors", async () =>
324
- withDir(async (dir) => {
325
- const maxBytes = DEFAULT_READ_MAX_BYTES;
326
- const hashLen = DEFAULT_CONFIG.hashLen;
327
- const prefixBytes = Buffer.byteLength(`1#${"X".repeat(hashLen)}│`);
328
- const first = "界".repeat(Math.floor(maxBytes / (2 * Buffer.byteLength("界"))));
329
- const second = "x".repeat(maxBytes - Buffer.byteLength(first) - 2 * prefixBytes);
330
- await writeFile(join(dir, "large.txt"), `${first}\n${second}\n`);
331
- const result = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "large.txt" });
332
- assert.equal(reportOf(result, "read")?.outputLimit, formatByteSize(maxBytes));
333
- assert.ok(result.content[0].text.includes(`1#${computeLineHash(1, first, hashLen)}│${first}`));
334
- assert.doesNotMatch(result.content[0].text, /\n2#/);
335
- const next = await call(makeReadOverride(dir, DEFAULT_CONFIG), {
336
- path: "large.txt",
337
- offset: 2,
338
- limit: 1,
339
- });
340
- assert.ok(next.content[0].text.includes(`2#${computeLineHash(2, second, hashLen)}│${second}`));
341
- }));
342
-
343
- test("read reports an oversized first row without suggesting an ineffective retry", async () =>
344
- withDir(async (dir) => {
345
- await writeFile(join(dir, "long.txt"), "x".repeat(DEFAULT_READ_MAX_BYTES));
346
- const result = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "long.txt" });
347
- assert.doesNotMatch(result.content[0].text, /^\d+#/m);
348
- assert.doesNotMatch(result.content[0].text, /use offset\/limit/);
349
- assert.equal(reportOf(result, "read")?.lineTooLong, formatByteSize(DEFAULT_READ_MAX_BYTES));
350
- assert.match(reportOf(result, "read")?.next ?? "", /chunks.*bash.*replace/);
351
- }));
352
-
353
- test("read preserves empty files and explicit limits above the native default", async () =>
354
- withDir(async (dir) => {
355
- await writeFile(join(dir, "empty.txt"), "");
356
- const empty = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "empty.txt" });
357
- assert.match(empty.content[0].text, /0 lines/);
358
- assert.equal(reportOf(empty, "read")?.nextOffset, undefined);
359
- await writeFile(join(dir, "many.txt"), "x\n".repeat(2001));
360
- const many = await call(makeReadOverride(dir, DEFAULT_CONFIG), {
361
- path: "many.txt",
362
- limit: 2001,
363
- });
364
- assert.match(many.content[0].text, /\n2001#[0-9A-Z]+│x/);
365
- assert.equal(reportOf(many, "read")?.nextOffset, undefined);
366
- }));
367
-
368
- test("read window end chosen by caller or default → only the default offers optional continuation", async () =>
369
- withDir(async (dir) => {
370
- const defaultLimit = DEFAULT_CONFIG.read.defaultLimit;
371
- const totalLines = defaultLimit + 100;
372
- await writeFile(
373
- join(dir, "large.txt"),
374
- Array.from({ length: totalLines }, (_, i) => `line${i + 1}\n`).join(""),
375
- );
376
- for (const limit of [undefined, defaultLimit, defaultLimit + 50]) {
377
- const result = await call(makeReadOverride(dir, DEFAULT_CONFIG), {
378
- path: "large.txt",
379
- limit,
380
- });
381
- const end = limit ?? defaultLimit;
382
- assert.match(result.content[0].text, new RegExp(`large\\.txt · ${totalLines} lines`));
383
- assert.match(result.content[0].text, new RegExp(`\\n${end}#[0-9A-Z]+│line${end}`));
384
- assert.doesNotMatch(result.content[0].text, new RegExp(`\\n${end + 1}#[0-9A-Z]+│`));
385
- const nextOffset = end + 1;
386
- const report = reportOf(result, "read");
387
- assert.ok(report);
388
- if (limit === undefined) {
389
- assert.equal(report.nextOffset, nextOffset);
390
- assert.match(report.next ?? "", /if you need more lines.*offset.*nextOffset/i);
391
- } else {
392
- assert.equal(Object.hasOwn(report, "nextOffset"), false);
393
- assert.equal(Object.hasOwn(report, "next"), false);
394
- }
395
- }
396
- }));
397
-
398
- test("read pagination supports offset windows and stops suggesting continuation at EOF", async () =>
399
- withDir(async (dir) => {
400
- const totalLines = DEFAULT_CONFIG.read.defaultLimit + 100;
401
- const start = 20;
402
- const end = start + DEFAULT_CONFIG.read.defaultLimit - 1;
403
- await writeFile(
404
- join(dir, "pages.txt"),
405
- Array.from({ length: totalLines }, (_, i) => `line${i + 1}\n`).join(""),
406
- );
407
- const read = makeReadOverride(dir, DEFAULT_CONFIG);
408
- const page = await call(read, { path: "pages.txt", offset: start });
409
- assert.match(reportOf(page, "read")?.next ?? "", /offset.*nextOffset/);
410
- const nextOffset = reportOf(page, "read")?.nextOffset;
411
- assert.ok(nextOffset);
412
- const next = await call(read, {
413
- path: "pages.txt",
414
- offset: nextOffset,
415
- });
416
- assert.match(next.content[0].text, new RegExp(`\\n${end + 1}#[0-9A-Z]+│line${end + 1}`));
417
- assert.match(next.content[0].text, new RegExp(`\\n${totalLines}#[0-9A-Z]+│line${totalLines}`));
418
- assert.equal(reportOf(next, "read")?.nextOffset, undefined);
419
- assert.equal(reportOf(next, "read")?.next, undefined);
420
- for (const offset of [totalLines - DEFAULT_CONFIG.read.defaultLimit + 1, totalLines + 1]) {
421
- const result = await call(read, { path: "pages.txt", offset });
422
- assert.equal(reportOf(result, "read")?.nextOffset, undefined);
423
- assert.equal(reportOf(result, "read")?.next, undefined);
424
- }
425
- }));
426
-
427
- test("read rejects noninteger and nonpositive offsets and limits before reading", async () =>
428
- withDir(async (dir) => {
429
- await writeFile(join(dir, "pages.txt"), "first\nsecond\nthird\n");
430
- const read = makeReadOverride(dir, DEFAULT_CONFIG);
431
- for (const key of ["offset", "limit"] as const) {
432
- const schema = read.parameters.properties[key];
433
- assert.equal(schema.type, "number");
434
- assert.equal("minimum" in schema ? schema.minimum : undefined, 1);
435
- assert.equal("multipleOf" in schema ? schema.multipleOf : undefined, 1);
436
- assert.equal("maximum" in schema ? schema.maximum : undefined, Number.MAX_SAFE_INTEGER);
437
- for (const invalid of [
438
- 0,
439
- -4,
440
- 0.5,
441
- 1.5,
442
- NaN,
443
- Infinity,
444
- -Infinity,
445
- Number.MAX_SAFE_INTEGER + 1,
446
- ]) {
447
- const params = { path: "pages.txt", [key]: invalid };
448
- await assert.rejects(call(read, params), rejectsArgument(key));
449
- }
450
- }
451
- assert.deepEqual(
452
- validateToolArguments(read as any, {
453
- type: "toolCall",
454
- id: "valid",
455
- name: "read",
456
- arguments: { path: "pages.txt", offset: 2, limit: 550 },
457
- }),
458
- { path: "pages.txt", offset: 2, limit: 550 },
459
- );
460
- await assert.rejects(call(read, { path: "missing.txt", offset: 1.5 }), rejectsArguments());
461
- }));
462
-
463
- test("read schema rejects empty paths and unknown fields before file access", async () =>
464
- withDir(async (dir) => {
465
- const read = makeReadOverride(dir, DEFAULT_CONFIG);
466
- const invalidArgs: Parameters<typeof validateToolArguments>[1]["arguments"][] = [
467
- { path: "" },
468
- { path: "missing.txt", offest: 3 },
469
- ];
470
- for (const args of invalidArgs) {
471
- await assert.rejects(call(read, args), rejectsArguments());
472
- }
473
- }));
474
-
475
- test("read byte truncation retains its budget and a continuation after complete returned rows", async () =>
476
- withDir(async (dir) => {
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);
488
- assert.match(reportOf(result, "read")?.next ?? "", /offset.*nextOffset/);
489
- assert.doesNotMatch(result.content[0].text, /showing lines|to continue/);
490
- }));
491
-
492
- test("read bounds oversized selected lines while reporting limits and preserving later anchors", async () =>
493
- withDir(async (dir) => {
494
- const long = "界".repeat(200_000);
495
- await writeFile(join(dir, "long.txt"), `first\r\n${long}\r\nlast`);
496
- const read = makeReadOverride(dir, DEFAULT_CONFIG);
497
- const result = await call(read, { path: "long.txt" });
498
- assert.match(result.content[0].text, /1#[0-9A-Z]+│first/);
499
- assert.doesNotMatch(result.content[0].text, /2#[0-9A-Z]+│/);
500
- assert.equal(reportOf(result, "read")?.lineTooLong, undefined);
501
- assert.equal(reportOf(result, "read")?.outputLimit, formatByteSize(DEFAULT_READ_MAX_BYTES));
502
- const oversized = await call(read, { path: "long.txt", offset: 2, limit: 1 });
503
- assert.equal(reportOf(oversized, "read")?.lineTooLong, formatByteSize(DEFAULT_READ_MAX_BYTES));
504
- assert.doesNotMatch(oversized.content[0].text, /^\d+#/m);
505
- const last = await call(read, { path: "long.txt", offset: 3, limit: 1 });
506
- assert.match(last.content[0].text, /3#[0-9A-Z]+│last/);
507
- assert.match(last.content[0].text, /no trailing newline/);
508
- }));
509
-
510
- test("read budgets visible standalone CR characters using rendered UTF-8 bytes", async () =>
511
- withDir(async (dir) => {
512
- const content = "\r".repeat(90_000);
513
- await writeFile(join(dir, "cr.txt"), content);
514
- const result = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "cr.txt", limit: 1 });
515
- assert.equal(reportOf(result, "read")?.lineTooLong, formatByteSize(DEFAULT_READ_MAX_BYTES));
516
- assert.doesNotMatch(result.content[0].text, /^\d+#/m);
517
- }));
518
-
519
- test("read renders native content without interpreting anchor-like prefixes", async () =>
520
- withDir(async (dir) => {
521
- const tool = makeReadOverride(dir, DEFAULT_CONFIG);
522
- for (const content of ["12#abc│ordinary content", "12#ABCD│ordinary content"]) {
523
- for (const suffix of ["\n", "\n\0tail"]) {
524
- await writeFile(join(dir, "prefix.txt"), content + suffix);
525
- const result = await call(tool, { path: "prefix.txt" });
526
- // Round-trip details as persisted session results do before rendering.
527
- const rendered = tool.renderResult!(
528
- JSON.parse(JSON.stringify(result)),
529
- { expanded: true, isPartial: false },
530
- stubTheme as Theme,
531
- { args: { path: "prefix.txt" }, state: {}, cwd: dir, isError: false } as any,
532
- )
533
- .render(120)
534
- .join("\n");
535
- assert.ok(rendered.includes(content), rendered);
536
- }
537
- }
538
- }));
539
-
540
- test("read accepts safe offsets and limits whose sum exceeds the safe integer range", async () =>
541
- withDir(async (dir) => {
542
- await writeFile(join(dir, "range.txt"), "first\nsecond\nthird\n");
543
- const tool = makeReadOverride(dir, DEFAULT_CONFIG);
544
- for (const offset of [2, 3, Number.MAX_SAFE_INTEGER]) {
545
- const result = await call(tool, {
546
- path: "range.txt",
547
- offset,
548
- limit: Number.MAX_SAFE_INTEGER,
549
- });
550
- assert.equal(reportOf(result, "read")?.nextOffset, undefined);
551
- assert.doesNotMatch(result.content[0].text, /to continue|│first/);
552
- if (offset <= 3) assert.match(result.content[0].text, /│third/);
553
- else assert.doesNotMatch(result.content[0].text, /│/);
554
- }
555
- }));
556
-
557
- test("Unicode line separators in a read path or middle row → renders every following row", async (t) => {
558
- const tool = makeReadOverride(process.cwd(), DEFAULT_CONFIG);
559
- const render = tool.renderResult;
560
- assert.ok(render);
561
- const formatter = createAnchorFormatter(DEFAULT_CONFIG.hashLen);
562
- for (const separator of ["\u2028", "\u2029"]) {
563
- for (const location of ["path", "middle row"]) {
564
- await t.test(`${location} ${JSON.stringify(separator)}`, () => {
565
- const path = location === "path" ? `before${separator}after.txt` : "read.txt";
566
- const lines = [
567
- "first",
568
- location === "middle row" ? `before${separator}after` : "middle",
569
- "third",
570
- "last",
571
- ];
572
- const header = `${path} · ${lines.length} lines`;
573
- const raw = [header, ...lines.map((line, index) => formatter.row(index + 1, line))].join(
574
- "\n",
575
- );
576
- const rendered = render(
577
- { content: [{ type: "text", text: raw }], details: undefined },
578
- { expanded: true, isPartial: false },
579
- stubTheme,
580
- {
581
- args: { path },
582
- state: {},
583
- cwd: process.cwd(),
584
- toolCallId: "unicode-read",
585
- lastComponent: undefined,
586
- invalidate() {},
587
- executionStarted: true,
588
- durationMs: undefined,
589
- outputPad: 1,
590
- keyText: () => "",
591
- keyHint: (_key, description) => description,
592
- argsComplete: true,
593
- isPartial: false,
594
- expanded: true,
595
- showImages: false,
596
- isError: false,
597
- },
598
- )
599
- .render(120)
600
- .map((line) => line.trimEnd());
601
- assert.deepEqual(rendered, [
602
- header,
603
- ...lines.map((line, index) => ` ${index + 1}: ${line}`),
604
- ]);
605
- });
606
- }
607
- }
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
- }));