@criogaid/pi-hashline-edit 0.5.0 → 0.6.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 (66) hide show
  1. package/README.md +66 -22
  2. package/package.json +6 -6
  3. package/src/core/apply.test.ts +66 -16
  4. package/src/core/apply.ts +36 -19
  5. package/src/core/lines.ts +3 -3
  6. package/src/core/text.test.ts +30 -1
  7. package/src/core/text.ts +8 -3
  8. package/src/index.ts +2 -0
  9. package/src/integration/forget-grep.test.ts +98 -0
  10. package/src/integration/fusion-dispatch.test.ts +343 -0
  11. package/src/integration/grep-rg.test.ts +466 -111
  12. package/src/integration/large-text.test.ts +3 -5
  13. package/src/integration/mutation-file-types.test.ts +44 -0
  14. package/src/pi/action-fusion.test.ts +158 -79
  15. package/src/pi/action-fusion.ts +105 -34
  16. package/src/pi/anchor-format.test.ts +46 -0
  17. package/src/pi/anchor-format.ts +21 -2
  18. package/src/pi/argument-validation.test.ts +136 -0
  19. package/src/pi/argument-validation.ts +103 -0
  20. package/src/pi/budgets.ts +4 -1
  21. package/src/pi/config.test.ts +1 -0
  22. package/src/pi/config.ts +4 -0
  23. package/src/pi/diagnostic-buffer.test.ts +58 -0
  24. package/src/pi/diagnostic-buffer.ts +59 -0
  25. package/src/pi/directory-sync.test.ts +1 -1
  26. package/src/pi/edit-tool.ts +56 -37
  27. package/src/pi/execute.test.ts +185 -645
  28. package/src/pi/failure-context.test.ts +4 -3
  29. package/src/pi/failure-path.test.ts +3 -3
  30. package/src/pi/file-commit.test.ts +24 -17
  31. package/src/pi/file-commit.ts +36 -9
  32. package/src/pi/file-snapshot.test.ts +24 -0
  33. package/src/pi/forget-tool.ts +268 -0
  34. package/src/pi/forget.test.ts +343 -0
  35. package/src/pi/forget.testing.ts +273 -0
  36. package/src/pi/fusion-card.test.ts +26 -0
  37. package/src/pi/fusion-card.ts +21 -6
  38. package/src/pi/grep-output.ts +82 -55
  39. package/src/pi/grep-render.ts +8 -11
  40. package/src/pi/grep-scope.ts +6 -31
  41. package/src/pi/grep-search.ts +94 -58
  42. package/src/pi/grep-tool.ts +50 -59
  43. package/src/pi/grep.test.ts +412 -208
  44. package/src/pi/mutation-result.test.ts +23 -0
  45. package/src/pi/mutation-runner.ts +8 -4
  46. package/src/pi/path.ts +16 -2
  47. package/src/pi/pi.test.ts +4 -3
  48. package/src/pi/read-tool.ts +59 -27
  49. package/src/pi/read.test.ts +361 -0
  50. package/src/pi/registration.test.ts +121 -4
  51. package/src/pi/render.test.ts +172 -15
  52. package/src/pi/render.ts +28 -5
  53. package/src/pi/replace-tool.ts +18 -27
  54. package/src/pi/replace.test.ts +8 -107
  55. package/src/pi/result-safety.test.ts +123 -149
  56. package/src/pi/rg-match-bytes.ts +95 -0
  57. package/src/pi/rg-process.test.ts +40 -59
  58. package/src/pi/rg-process.ts +8 -5
  59. package/src/pi/rg-text-view.ts +59 -9
  60. package/src/pi/text-stream.test.ts +153 -0
  61. package/src/pi/text-stream.ts +33 -13
  62. package/src/pi/tool-call.testing.ts +50 -0
  63. package/src/pi/tool-prompts.ts +15 -0
  64. package/src/pi/write-tool.ts +19 -26
  65. package/src/pi/write.test.ts +70 -61
  66. package/src/pi/e2e-scenarios.test.ts +0 -360
@@ -84,3 +84,26 @@ test("mutation anchors reserve the notice after overflow and retain later fittin
84
84
  assert.ok(report.includes(`${anchors.row(2, lines[1])}\n${anchors.row(3, lines[2])}`));
85
85
  }
86
86
  });
87
+
88
+ test("compact mutation anchors have no row cap and stop at the byte budget", () => {
89
+ const anchors = createAnchorFormatter(4);
90
+ for (const count of [80, 3000]) {
91
+ const lines = Array.from({ length: count }, (_, index) => `changed ${index}`);
92
+ const report = formatMutationAnchors([], lines, lines.keys(), anchors, "Updated anchors:");
93
+ const rows = report.match(/^\d+#[0-9A-Z]+$/gm) ?? [];
94
+ assert.ok(rows.length > 40);
95
+ assert.doesNotMatch(report, /│/);
96
+ assert.ok(Buffer.byteLength(report) <= MAX_BLOCK_BYTES);
97
+ if (count === 80) {
98
+ assert.equal(rows.length, count);
99
+ assert.doesNotMatch(report, /omitted/);
100
+ } else {
101
+ assert.ok(rows.length < count);
102
+ assert.match(report, /additional anchors omitted/);
103
+ }
104
+ assert.deepEqual(
105
+ rows,
106
+ lines.slice(0, rows.length).map((line, index) => anchors.token(index + 1, line)),
107
+ );
108
+ }
109
+ });
@@ -16,11 +16,12 @@
16
16
  * @module pi-hashline-edit/pi
17
17
  */
18
18
 
19
- import { withFileMutationQueue, type ExtensionContext } from "@earendil-works/pi-coding-agent";
19
+ import { withFileMutationQueue, type ExtensionToolContext } from "@earendil-works/pi-coding-agent";
20
20
  import type { AgentToolResult, AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
21
21
  import type {
22
22
  ActionFusionDetails,
23
23
  createActionFusionExecutor,
24
+ MutationToolName,
24
25
  ThenRunInput,
25
26
  } from "./action-fusion.ts";
26
27
  import { commitReplacement, readEditableSnapshot } from "./file-commit.ts";
@@ -35,7 +36,6 @@ import { canonicalPath } from "./path.ts";
35
36
  import { throwIfCancelled } from "./error-text.ts";
36
37
 
37
38
  export type ActionFusionExecutor = ReturnType<typeof createActionFusionExecutor>;
38
- export type MutationToolName = "edit" | "replace" | "write";
39
39
 
40
40
  /** Result details shared by the read-modify-write tools. */
41
41
  export type TextMutationDetails = ReturnType<typeof generateMutationDetails> & {
@@ -63,7 +63,7 @@ export interface MutationCall<TParams, TDetails> {
63
63
  readonly params: TParams & { then_run?: ThenRunInput };
64
64
  readonly signal: AbortSignal | undefined;
65
65
  readonly onUpdate: AgentToolUpdateCallback<TDetails> | undefined;
66
- readonly ctx: ExtensionContext;
66
+ readonly ctx: ExtensionToolContext;
67
67
  }
68
68
 
69
69
  /** Queue and publish one validated mutation call, then run its then_run command when fused. */
@@ -116,7 +116,11 @@ export async function runTextMutation(
116
116
  ): Promise<MutationOutcome<TextMutationDetails>> {
117
117
  const { absolutePath, displayPath, signal } = target;
118
118
 
119
- const { text: currentText, baseRevision } = await readEditableSnapshot(absolutePath, displayPath);
119
+ const { text: currentText, baseRevision } = await readEditableSnapshot(
120
+ absolutePath,
121
+ displayPath,
122
+ signal,
123
+ );
120
124
  // Cancelled after read: don't transform; the file stays untouched.
121
125
  throwIfCancelled(signal, `before apply; ${displayPath} was not changed.`);
122
126
 
package/src/pi/path.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { homedir } from "node:os";
2
- import { isAbsolute, join, resolve } from "node:path";
3
- import { fileURLToPath } from "node:url";
2
+ import { isAbsolute, join, relative, resolve, sep } from "node:path";
3
+ import { fileURLToPath, pathToFileURL } from "node:url";
4
4
 
5
5
  const UNICODE_SPACES = /[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g;
6
6
  const WINDOWS_SHELL_DRIVE = /^\/(?:mnt\/|cygdrive\/)?([a-z])(?:\/(.*))?$/i;
@@ -28,3 +28,17 @@ export function canonicalPath(cwd: string, path: string): string {
28
28
  if (normalized.startsWith("file://")) normalized = fileURLToPath(normalized);
29
29
  return isAbsolute(normalized) ? resolve(normalized) : resolve(cwd, normalized);
30
30
  }
31
+
32
+ /** Return a readable path that resolves back to the same file through the tools' input syntax. */
33
+ export function serializePath(cwd: string, path: string): string {
34
+ const absolute = resolve(cwd, path);
35
+ const rel = relative(cwd, absolute);
36
+ const local = rel && rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
37
+ const candidate = local ? (sep === "\\" ? rel.replaceAll(sep, "/") : rel) : absolute;
38
+ // A file URL preserves names whose spaces are normalized on input, and keeps headers single-line.
39
+ if (!/[\r\n]/.test(candidate)) {
40
+ if (canonicalPath(cwd, candidate) === absolute) return candidate;
41
+ if (local && canonicalPath(cwd, `./${candidate}`) === absolute) return `./${candidate}`;
42
+ }
43
+ return pathToFileURL(absolute).href;
44
+ }
package/src/pi/pi.test.ts CHANGED
@@ -73,7 +73,7 @@ test("file tools share Pi-style URL and @ path resolution", async () => {
73
73
  const ctx = { cwd: dir } as Parameters<ReturnType<typeof makeReadOverride>["execute"]>[4];
74
74
  await callTool(
75
75
  makeWriteOverride(dir),
76
- { path: `@${url}`, content: "before\n" },
76
+ { path: `@${url}`, content: "before\n", mode: "create" },
77
77
  {
78
78
  toolCallId: "write",
79
79
  ctx,
@@ -101,7 +101,7 @@ test("file tools share Pi-style URL and @ path resolution", async () => {
101
101
  );
102
102
  const matches = await callTool(
103
103
  makeGrepOverride(dir, DEFAULT_CONFIG),
104
- { path: `@${url}`, pattern: "edited" },
104
+ { path: `@${url}`, pattern: "edited", literal: true },
105
105
  { toolCallId: "grep" },
106
106
  );
107
107
  assert.match(matches.content[0].text, /edited/);
@@ -109,13 +109,14 @@ test("file tools share Pi-style URL and @ path resolution", async () => {
109
109
  let commands = 0;
110
110
  const fusion = createActionFusionExecutor(async () => {
111
111
  commands++;
112
- return "checked";
112
+ return { status: "succeeded", output: "checked" };
113
113
  });
114
114
  const fused = await callTool(
115
115
  makeWriteOverride(dir, fusion),
116
116
  {
117
117
  path: `@${url}`,
118
118
  content: "edited\n",
119
+ mode: "overwrite",
119
120
  then_run: { command: "check" },
120
121
  },
121
122
  { toolCallId: "fused", ctx },
@@ -16,24 +16,32 @@ import {
16
16
  highlightCode,
17
17
  type ReadToolInput,
18
18
  type ReadToolDetails,
19
- type ExtensionContext,
19
+ type ExtensionToolContext,
20
20
  type Theme,
21
21
  type ToolDefinition,
22
22
  } from "@earendil-works/pi-coding-agent";
23
23
  import type { AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
24
24
  import { Text } from "@earendil-works/pi-tui";
25
+ import { Type } from "typebox";
25
26
  import { scanTextLines } from "./text-stream.ts";
26
27
  import { createAnchorFormatter, displayCarriageReturns, parseHashline } from "./anchor-format.ts";
27
28
  import { canonicalPath } from "./path.ts";
28
29
  import { renderToolError } from "./render.ts";
30
+ import {
31
+ type ForgetReceiptDetails,
32
+ readReceipt,
33
+ withoutResultTag,
34
+ withResultTag,
35
+ } from "./forget-tool.ts";
29
36
  import { POSITIVE_SAFE_INTEGER } from "./schema.ts";
30
37
  import { throwIfCancelled } from "./error-text.ts";
31
38
  import { formatKiB } from "./budgets.ts";
32
39
  import type { HashlineEditConfig } from "./config.ts";
40
+ import { createArgumentPreparer } from "./argument-validation.ts";
33
41
 
34
42
  const DEFAULT_OFFSET = 1;
35
43
 
36
- type ReadDetails = ReadToolDetails & { nativeRead?: true };
44
+ type ReadDetails = ReadToolDetails & { nativeRead?: true } & ForgetReceiptDetails;
37
45
 
38
46
  /**
39
47
  * First result line: `<path> · <N> lines`, optionally ` (from line <offset>)` and
@@ -121,24 +129,26 @@ export function makeReadOverride(
121
129
  const { defaultLimit } = config.read;
122
130
  const maxBytes = config.read.maxKiB * 1024;
123
131
  const builtin = createReadToolDefinition(cwd);
124
- const parameters = {
125
- ...builtin.parameters,
126
- additionalProperties: false,
127
- properties: {
128
- ...builtin.parameters.properties,
129
- path: { ...builtin.parameters.properties.path, minLength: 1 },
130
- offset: {
131
- ...builtin.parameters.properties.offset,
132
- ...POSITIVE_SAFE_INTEGER,
133
- description: `1-based line to start from (default ${DEFAULT_OFFSET}).`,
134
- },
135
- limit: {
136
- ...builtin.parameters.properties.limit,
137
- ...POSITIVE_SAFE_INTEGER,
138
- description: `Maximum lines to read (default ${defaultLimit}).`,
139
- },
132
+ // A TypeBox object, not a spread of Pi's plain JSON schema: argument diagnostics pick
133
+ // single fields from it, which needs TypeBox's own schema kinds.
134
+ const parameters = Type.Object(
135
+ {
136
+ path: Type.String({ ...builtin.parameters.properties.path, minLength: 1 }),
137
+ offset: Type.Optional(
138
+ Type.Number({
139
+ ...POSITIVE_SAFE_INTEGER,
140
+ description: `1-based line to start from (default ${DEFAULT_OFFSET}).`,
141
+ }),
142
+ ),
143
+ limit: Type.Optional(
144
+ Type.Number({
145
+ ...POSITIVE_SAFE_INTEGER,
146
+ description: `Maximum lines to read (default ${defaultLimit}).`,
147
+ }),
148
+ ),
140
149
  },
141
- };
150
+ { additionalProperties: false },
151
+ );
142
152
 
143
153
  return {
144
154
  name: "read" as const,
@@ -151,6 +161,7 @@ export function makeReadOverride(
151
161
  "For large files, pass read offset and limit to read only the relevant section.",
152
162
  ],
153
163
  parameters: parameters as typeof builtin.parameters,
164
+ prepareArguments: createArgumentPreparer("read", parameters),
154
165
  renderShell: "default" as const,
155
166
 
156
167
  renderCall: builtin.renderCall,
@@ -159,8 +170,9 @@ export function makeReadOverride(
159
170
  const { isPartial, expanded } = options;
160
171
  if (isPartial) return new Text(theme.fg("warning", "Reading…"), 0, 0);
161
172
  const content = result.content?.[0];
162
- if (context?.isError) return renderToolError(result, theme);
163
- if (result.details?.nativeRead) return builtin.renderResult!(result, options, theme, context);
173
+ if (context?.isError) return renderToolError(result, theme, expanded);
174
+ if (result.details?.nativeRead)
175
+ return builtin.renderResult!(withoutResultTag(result), options, theme, context);
164
176
  // Collapsed (not expanded): show nothing — the call line carries the
165
177
  // title, matching the built-in read's fold behavior.
166
178
  if (!expanded) return new Text("", 0, 0);
@@ -173,7 +185,7 @@ export function makeReadOverride(
173
185
  params: ReadToolInput,
174
186
  signal: AbortSignal | undefined,
175
187
  onUpdate: AgentToolUpdateCallback<ReadToolDetails | undefined> | undefined,
176
- ctx: ExtensionContext,
188
+ ctx: ExtensionToolContext,
177
189
  ) {
178
190
  throwIfCancelled(signal);
179
191
  const offset = params.offset ?? DEFAULT_OFFSET;
@@ -181,7 +193,16 @@ export function makeReadOverride(
181
193
  const anchors = createAnchorFormatter(hashLen);
182
194
  const readNative = async () => {
183
195
  const result = await builtin.execute(toolCallId, params, signal, onUpdate, ctx);
184
- return { ...result, details: { ...result.details, nativeRead: true as const } };
196
+ return withResultTag(
197
+ toolCallId,
198
+ { ...result, details: { ...result.details, nativeRead: true as const } },
199
+ config.forget,
200
+ () =>
201
+ readReceipt(
202
+ params.path,
203
+ result.content.some((block) => block.type === "image") ? { image: true } : undefined,
204
+ ),
205
+ );
185
206
  };
186
207
 
187
208
  const absPath = canonicalPath(cwd, params.path as string);
@@ -265,10 +286,21 @@ export function makeReadOverride(
265
286
  const header = `${formatReadHeader(params.path, stats.totalLines, start, stats.finalNewline)}\n`;
266
287
  const body = truncation.content;
267
288
 
268
- return {
269
- content: [{ type: "text" as const, text: header + body + tail }],
270
- details: truncation.truncated ? { truncation } : pagination ? { pagination } : undefined,
271
- };
289
+ return withResultTag(
290
+ toolCallId,
291
+ {
292
+ content: [{ type: "text" as const, text: header + body + tail }],
293
+ details: truncation.truncated ? { truncation } : pagination ? { pagination } : undefined,
294
+ },
295
+ config.forget,
296
+ () =>
297
+ readReceipt(
298
+ params.path,
299
+ rows.length > 0
300
+ ? { start, end: start + rows.length - 1, truncated: truncation.truncated }
301
+ : undefined,
302
+ ),
303
+ );
272
304
  },
273
305
  };
274
306
  }
@@ -0,0 +1,361 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { mkdtemp, rm, readFile, writeFile } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { initTheme } from "@earendil-works/pi-coding-agent";
7
+ import type { Theme } from "@earendil-works/pi-coding-agent";
8
+ import { validateToolArguments } from "@earendil-works/pi-ai";
9
+ import { makeReadOverride } from "./read-tool.ts";
10
+ import { computeLineHash } from "../core/hash.ts";
11
+ import { callTool } from "./tool-call.testing.ts";
12
+ import { DEFAULT_CONFIG } from "./config.ts";
13
+ import { FORGET_MIN_BYTES, formatKiB } from "./budgets.ts";
14
+ import { taggedResultId } from "./forget.testing.ts";
15
+
16
+ const DEFAULT_READ_MAX_BYTES = DEFAULT_CONFIG.read.maxKiB * 1024;
17
+
18
+ async function withDir<T>(fn: (dir: string) => Promise<T>): Promise<T> {
19
+ const dir = await mkdtemp(join(tmpdir(), "hl-"));
20
+ try {
21
+ return await fn(dir);
22
+ } finally {
23
+ await rm(dir, { recursive: true, force: true });
24
+ }
25
+ }
26
+
27
+ /** Call a tool through Pi's argument preparation and schema validation, as production does. */
28
+ const call = (tool: any, params: any) => callTool(tool, params, { toolCallId: "0" });
29
+
30
+ const stubTheme = { fg: (_k: string, s: string) => s, bold: (s: string) => s } as Theme;
31
+
32
+ initTheme();
33
+
34
+ test("read execute: text outputs LINE#HASH│content", async () => {
35
+ await withDir(async (dir) => {
36
+ await writeFile(join(dir, "f.txt"), "line1\nline2\n");
37
+ const r: any = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "f.txt" });
38
+ const text = r.content[0];
39
+ assert.equal(text.type, "text");
40
+ assert.match(text.text, /1#[0-9A-Z]+│line1/);
41
+ assert.match(text.text, /2#[0-9A-Z]+│line2/);
42
+ assert.match(text.text, /f\.txt · 2 lines/);
43
+ });
44
+ });
45
+
46
+ test("read execute: Pi-supported images without NUL bypass text decoding", async () =>
47
+ withDir(async (dir) => {
48
+ for (const [name, bytes, mime] of [
49
+ ["picture.jpg", Buffer.from([0xff, 0xd8, 0xff, 0xd9]), "image/jpeg"],
50
+ ["picture.gif", Buffer.from("GIF89a"), "image/gif"],
51
+ ] as const) {
52
+ await writeFile(join(dir, name), bytes);
53
+ const result: any = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: name });
54
+ assert.ok(result.content[0].text.startsWith(`Read image file [${mime}]`));
55
+ assert.deepEqual(await readFile(join(dir, name)), bytes);
56
+ }
57
+ }));
58
+
59
+ test("read execute: a missing final newline is stated in the header", async () => {
60
+ await withDir(async (dir) => {
61
+ await writeFile(join(dir, "f.txt"), "line1\nline2");
62
+ const bare: any = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "f.txt" });
63
+ assert.match(bare.content[0].text, /f\.txt · 2 lines · no trailing newline/);
64
+
65
+ await writeFile(join(dir, "g.txt"), "line1\nline2\n");
66
+ const terminated: any = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "g.txt" });
67
+ assert.doesNotMatch(terminated.content[0].text, /no trailing newline/);
68
+ });
69
+ });
70
+
71
+ test("hash length stays 4 even for runs of identical lines (no explosion)", async () => {
72
+ await withDir(async (dir) => {
73
+ const f = join(dir, "f.txt");
74
+ await writeFile(f, "\n\n\n\ncode\n");
75
+ const r: any = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "f.txt" });
76
+ const text: string = r.content[0].text;
77
+ for (const m of text.matchAll(/\d+#([0-9A-Z]+)│/g)) {
78
+ assert.equal(m[1].length, 4, `anchor ${m[0]} hash is not 4 chars`);
79
+ }
80
+ });
81
+ });
82
+
83
+ test("read byte truncation counts UTF-8 and separators without cutting anchors", async () =>
84
+ withDir(async (dir) => {
85
+ const maxBytes = DEFAULT_READ_MAX_BYTES;
86
+ const hashLen = DEFAULT_CONFIG.hashLen;
87
+ const prefixBytes = Buffer.byteLength(`1#${"X".repeat(hashLen)}│`);
88
+ const first = "界".repeat(40000);
89
+ const second = "x".repeat(maxBytes - Buffer.byteLength(first) - 2 * prefixBytes);
90
+ await writeFile(join(dir, "large.txt"), `${first}\n${second}\n`);
91
+ const result = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "large.txt" });
92
+ assert.equal(result.details.truncation.outputLines, 1);
93
+ assert.equal(result.details.truncation.truncatedBy, "bytes");
94
+ assert.equal(result.details.truncation.maxBytes, maxBytes);
95
+ assert.match(result.content[0].text, new RegExp(`truncated.*${formatKiB(maxBytes)}`));
96
+ assert.ok(
97
+ result.content[0].text.includes(`1#${computeLineHash(1, first, hashLen)}│${first}\n`),
98
+ );
99
+ assert.doesNotMatch(result.content[0].text, /\n2#/);
100
+ const next = await call(makeReadOverride(dir, DEFAULT_CONFIG), {
101
+ path: "large.txt",
102
+ offset: 2,
103
+ limit: 1,
104
+ });
105
+ assert.ok(next.content[0].text.includes(`2#${computeLineHash(2, second, hashLen)}│${second}`));
106
+ }));
107
+
108
+ test("read reports an oversized first row without suggesting an ineffective retry", async () =>
109
+ withDir(async (dir) => {
110
+ await writeFile(join(dir, "long.txt"), "x".repeat(DEFAULT_READ_MAX_BYTES));
111
+ const result = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "long.txt" });
112
+ assert.equal(result.details.truncation.firstLineExceedsLimit, true);
113
+ assert.equal(result.details.truncation.outputLines, 0);
114
+ assert.doesNotMatch(result.content[0].text, /^\d+#/m);
115
+ assert.doesNotMatch(result.content[0].text, /use offset\/limit/);
116
+ assert.match(result.content[0].text, /cannot split.*line/);
117
+ assert.match(result.content[0].text, /bash.*chunks.*replace/);
118
+ }));
119
+
120
+ test("read preserves empty files and explicit limits above the native default", async () =>
121
+ withDir(async (dir) => {
122
+ await writeFile(join(dir, "empty.txt"), "");
123
+ const empty = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "empty.txt" });
124
+ assert.match(empty.content[0].text, /0 lines/);
125
+ assert.equal(empty.details, undefined);
126
+ await writeFile(join(dir, "many.txt"), "x\n".repeat(2001));
127
+ const many = await call(makeReadOverride(dir, DEFAULT_CONFIG), {
128
+ path: "many.txt",
129
+ limit: 2001,
130
+ });
131
+ assert.match(many.content[0].text, /\n2001#[0-9A-Z]+│x/);
132
+ assert.equal(many.details, undefined);
133
+ }));
134
+
135
+ test("read uses the configured default limit and respects explicit limits", async () =>
136
+ withDir(async (dir) => {
137
+ const defaultLimit = DEFAULT_CONFIG.read.defaultLimit;
138
+ const totalLines = defaultLimit + 100;
139
+ await writeFile(
140
+ join(dir, "large.txt"),
141
+ Array.from({ length: totalLines }, (_, i) => `line${i + 1}\n`).join(""),
142
+ );
143
+ for (const limit of [undefined, defaultLimit + 50]) {
144
+ const result = await call(makeReadOverride(dir, DEFAULT_CONFIG), {
145
+ path: "large.txt",
146
+ limit,
147
+ });
148
+ const end = limit ?? defaultLimit;
149
+ assert.match(result.content[0].text, new RegExp(`large\\.txt · ${totalLines} lines`));
150
+ assert.match(result.content[0].text, new RegExp(`\\n${end}#[0-9A-Z]+│line${end}`));
151
+ assert.doesNotMatch(result.content[0].text, new RegExp(`\\n${end + 1}#[0-9A-Z]+│`));
152
+ assert.deepEqual(result.details, {
153
+ pagination: { start: 1, end, totalLines, nextOffset: end + 1 },
154
+ });
155
+ assert.match(result.content[0].text, new RegExp(`offset ${end + 1}`));
156
+ }
157
+ }));
158
+
159
+ test("read pagination supports offset windows and stops suggesting continuation at EOF", async () =>
160
+ withDir(async (dir) => {
161
+ const totalLines = DEFAULT_CONFIG.read.defaultLimit + 100;
162
+ const start = 20;
163
+ const end = start + DEFAULT_CONFIG.read.defaultLimit - 1;
164
+ await writeFile(
165
+ join(dir, "pages.txt"),
166
+ Array.from({ length: totalLines }, (_, i) => `line${i + 1}\n`).join(""),
167
+ );
168
+ const read = makeReadOverride(dir, DEFAULT_CONFIG);
169
+ const page = await call(read, { path: "pages.txt", offset: start });
170
+ assert.match(page.content[0].text, new RegExp(`offset ${end + 1}`));
171
+ assert.deepEqual(page.details, {
172
+ pagination: { start, end, totalLines, nextOffset: end + 1 },
173
+ });
174
+ const next = await call(read, {
175
+ path: "pages.txt",
176
+ offset: page.details.pagination.nextOffset,
177
+ });
178
+ assert.match(next.content[0].text, new RegExp(`\\n${end + 1}#[0-9A-Z]+│line${end + 1}`));
179
+ assert.match(next.content[0].text, new RegExp(`\\n${totalLines}#[0-9A-Z]+│line${totalLines}`));
180
+ assert.equal(next.details, undefined);
181
+ assert.doesNotMatch(next.content[0].text, /to continue/);
182
+ for (const offset of [totalLines - DEFAULT_CONFIG.read.defaultLimit + 1, totalLines + 1]) {
183
+ const result = await call(read, { path: "pages.txt", offset });
184
+ assert.equal(result.details, undefined);
185
+ assert.doesNotMatch(result.content[0].text, /to continue/);
186
+ }
187
+ }));
188
+
189
+ test("read rejects noninteger and nonpositive offsets and limits before reading", async () =>
190
+ withDir(async (dir) => {
191
+ await writeFile(join(dir, "pages.txt"), "first\nsecond\nthird\n");
192
+ const read = makeReadOverride(dir, DEFAULT_CONFIG);
193
+ for (const key of ["offset", "limit"] as const) {
194
+ const schema = read.parameters.properties[key];
195
+ assert.equal(schema.type, "number");
196
+ assert.equal("minimum" in schema ? schema.minimum : undefined, 1);
197
+ assert.equal("multipleOf" in schema ? schema.multipleOf : undefined, 1);
198
+ assert.equal("maximum" in schema ? schema.maximum : undefined, Number.MAX_SAFE_INTEGER);
199
+ for (const invalid of [
200
+ 0,
201
+ -4,
202
+ 0.5,
203
+ 1.5,
204
+ NaN,
205
+ Infinity,
206
+ -Infinity,
207
+ Number.MAX_SAFE_INTEGER + 1,
208
+ ]) {
209
+ const params = { path: "pages.txt", [key]: invalid };
210
+ await assert.rejects(
211
+ call(read, params),
212
+ new RegExp(`Validation failed for tool "read":\\n {2}- ${key}: `),
213
+ );
214
+ }
215
+ }
216
+ assert.deepEqual(
217
+ validateToolArguments(read as any, {
218
+ type: "toolCall",
219
+ id: "valid",
220
+ name: "read",
221
+ arguments: { path: "pages.txt", offset: 2, limit: 550 },
222
+ }),
223
+ { path: "pages.txt", offset: 2, limit: 550 },
224
+ );
225
+ await assert.rejects(
226
+ call(read, { path: "missing.txt", offset: 1.5 }),
227
+ /Validation failed for tool "read"/,
228
+ );
229
+ const page = await call(read, { path: "pages.txt", offset: 2, limit: 1 });
230
+ assert.match(page.content[0].text, /\n2#[0-9A-Z]+│second/);
231
+ assert.match(page.content[0].text, /offset 3/);
232
+ assert.deepEqual(page.details, {
233
+ pagination: { start: 2, end: 2, totalLines: 3, nextOffset: 3 },
234
+ });
235
+ await writeFile(join(dir, "long.txt"), "x".repeat(DEFAULT_READ_MAX_BYTES + 1));
236
+ const long = await call(read, { path: "long.txt", offset: 1, limit: 1 });
237
+ assert.equal(long.details.truncation.firstLineExceedsLimit, true);
238
+ assert.equal(long.details.truncation.outputLines, 0);
239
+ assert.equal(long.details.truncation.maxBytes, DEFAULT_READ_MAX_BYTES);
240
+ }));
241
+
242
+ test("read schema rejects empty paths and unknown fields before file access", async () =>
243
+ withDir(async (dir) => {
244
+ const read = makeReadOverride(dir, DEFAULT_CONFIG);
245
+ const invalidArgs: Parameters<typeof validateToolArguments>[1]["arguments"][] = [
246
+ { path: "" },
247
+ { path: "missing.txt", offest: 3 },
248
+ ];
249
+ for (const args of invalidArgs) {
250
+ await assert.rejects(call(read, args), /Validation failed for tool "read"/);
251
+ }
252
+ }));
253
+
254
+ test("read byte truncation takes precedence over line pagination", async () =>
255
+ withDir(async (dir) => {
256
+ await writeFile(join(dir, "large.txt"), `first\n${"x".repeat(DEFAULT_READ_MAX_BYTES)}\ntail\n`);
257
+ const result = await call(makeReadOverride(dir, DEFAULT_CONFIG), {
258
+ path: "large.txt",
259
+ limit: 2,
260
+ });
261
+ assert.equal(result.details.truncation.truncatedBy, "bytes");
262
+ assert.equal(result.details.pagination, undefined);
263
+ assert.equal(result.details.truncation.maxBytes, DEFAULT_READ_MAX_BYTES);
264
+ assert.doesNotMatch(result.content[0].text, /showing lines|to continue/);
265
+ }));
266
+
267
+ test("read bounds oversized selected lines while preserving truncation metadata and later anchors", async () =>
268
+ withDir(async (dir) => {
269
+ const long = "界".repeat(200_000);
270
+ await writeFile(join(dir, "long.txt"), `first\r\n${long}\r\nlast`);
271
+ const read = makeReadOverride(dir, DEFAULT_CONFIG);
272
+ const result = await call(read, { path: "long.txt" });
273
+ assert.match(result.content[0].text, /1#[0-9A-Z]+│first/);
274
+ assert.doesNotMatch(result.content[0].text, /2#[0-9A-Z]+│/);
275
+ assert.equal(result.details.truncation.firstLineExceedsLimit, false);
276
+ assert.equal(result.details.truncation.outputLines, 1);
277
+ const expectedRows = ["first", long, "last"].map(
278
+ (text, index) => `${index + 1}#${computeLineHash(index + 1, text, 4)}│${text}`,
279
+ );
280
+ assert.equal(result.details.truncation.totalBytes, Buffer.byteLength(expectedRows.join("\n")));
281
+ const oversized = await call(read, { path: "long.txt", offset: 2, limit: 1 });
282
+ assert.equal(oversized.details.truncation.firstLineExceedsLimit, true);
283
+ assert.equal(oversized.details.truncation.outputBytes, 0);
284
+ const last = await call(read, { path: "long.txt", offset: 3, limit: 1 });
285
+ assert.match(last.content[0].text, /3#[0-9A-Z]+│last/);
286
+ assert.match(last.content[0].text, /no trailing newline/);
287
+ }));
288
+
289
+ test("read budgets visible standalone CR characters using rendered UTF-8 bytes", async () =>
290
+ withDir(async (dir) => {
291
+ const content = "\r".repeat(90_000);
292
+ await writeFile(join(dir, "cr.txt"), content);
293
+ const result = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "cr.txt", limit: 1 });
294
+ assert.equal(result.details.truncation.firstLineExceedsLimit, true);
295
+ assert.equal(result.details.truncation.outputBytes, 0);
296
+ assert.equal(
297
+ result.details.truncation.totalBytes,
298
+ Buffer.byteLength(`1#${computeLineHash(1, content, 4)}│${"␍".repeat(content.length)}`),
299
+ );
300
+ }));
301
+
302
+ test("read renders native content without interpreting anchor-like prefixes", async () =>
303
+ withDir(async (dir) => {
304
+ const tool = makeReadOverride(dir, DEFAULT_CONFIG);
305
+ for (const content of ["12#abc│ordinary content", "12#ABCD│ordinary content"]) {
306
+ for (const suffix of ["\n", "\n\0tail"]) {
307
+ await writeFile(join(dir, "prefix.txt"), content + suffix);
308
+ const result = await call(tool, { path: "prefix.txt" });
309
+ // Round-trip details as persisted session results do before rendering.
310
+ const rendered = tool.renderResult!(
311
+ JSON.parse(JSON.stringify(result)),
312
+ { expanded: true, isPartial: false },
313
+ stubTheme as Theme,
314
+ { args: { path: "prefix.txt" }, state: {}, cwd: dir, isError: false } as any,
315
+ )
316
+ .render(120)
317
+ .join("\n");
318
+ assert.ok(rendered.includes(content), rendered);
319
+ }
320
+ }
321
+ }));
322
+
323
+ test("read accepts safe offsets and limits whose sum exceeds the safe integer range", async () =>
324
+ withDir(async (dir) => {
325
+ await writeFile(join(dir, "range.txt"), "first\nsecond\nthird\n");
326
+ const tool = makeReadOverride(dir, DEFAULT_CONFIG);
327
+ for (const offset of [2, 3, Number.MAX_SAFE_INTEGER]) {
328
+ const result = await call(tool, {
329
+ path: "range.txt",
330
+ offset,
331
+ limit: Number.MAX_SAFE_INTEGER,
332
+ });
333
+ assert.equal(result.details, undefined);
334
+ assert.doesNotMatch(result.content[0].text, /to continue|│first/);
335
+ if (offset <= 3) assert.match(result.content[0].text, /│third/);
336
+ else assert.doesNotMatch(result.content[0].text, /│/);
337
+ }
338
+ }));
339
+
340
+ test("read text reaches the forget byte threshold → only eligible results receive a tag", async () =>
341
+ withDir(async (dir) => {
342
+ const path = join(dir, "threshold.txt");
343
+ const read = makeReadOverride(dir, { ...DEFAULT_CONFIG, forget: true });
344
+ await writeFile(path, "界\n");
345
+ const initial: Awaited<ReturnType<typeof read.execute>> = await callTool(read, { path });
346
+ const initialBlock = initial.content[0];
347
+ assert.ok(initialBlock.type === "text");
348
+ const initialBytes = Buffer.byteLength(initialBlock.text);
349
+ for (const bytes of [FORGET_MIN_BYTES - 1, FORGET_MIN_BYTES, FORGET_MIN_BYTES + 1]) {
350
+ await writeFile(path, `界${"x".repeat(bytes - initialBytes)}\n`);
351
+ const result: Awaited<ReturnType<typeof read.execute>> = await callTool(
352
+ read,
353
+ { path },
354
+ { toolCallId: `read-${bytes}` },
355
+ );
356
+ const body = result.content[0];
357
+ assert.ok(body.type === "text");
358
+ assert.equal(Buffer.byteLength(body.text), bytes);
359
+ assert.equal(taggedResultId(result) !== undefined, bytes >= FORGET_MIN_BYTES);
360
+ }
361
+ }));