@criogaid/pi-hashline-edit 0.7.0 → 0.9.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 (118) hide show
  1. package/README.md +76 -220
  2. package/README.zh-CN.md +166 -0
  3. package/package.json +2 -1
  4. package/src/core/AGENTS.md +1 -1
  5. package/src/core/apply.test.ts +171 -133
  6. package/src/core/apply.ts +34 -31
  7. package/src/core/case-fold.test.ts +11 -7
  8. package/src/core/case-fold.ts +2 -6
  9. package/src/core/character-set.ts +14 -0
  10. package/src/core/hash.test.ts +1 -25
  11. package/src/core/hash.ts +0 -5
  12. package/src/core/lines.ts +25 -7
  13. package/src/core/ranges.test.ts +49 -9
  14. package/src/core/ranges.ts +15 -4
  15. package/src/core/regex.ts +36 -6
  16. package/src/core/replace-schema.ts +18 -11
  17. package/src/core/replace.test.ts +90 -0
  18. package/src/core/replace.ts +6 -5
  19. package/src/core/search-analysis.test.ts +9 -0
  20. package/src/core/search-analysis.ts +35 -31
  21. package/src/core/search.ts +1 -1
  22. package/src/core/types.ts +6 -8
  23. package/src/index.ts +2 -4
  24. package/src/integration/config-registration.test.ts +18 -10
  25. package/src/integration/fusion-dispatch.test.ts +41 -22
  26. package/src/integration/grep-flags.test.ts +6 -13
  27. package/src/integration/grep-js-completeness.test.ts +41 -31
  28. package/src/integration/grep-order.test.ts +78 -0
  29. package/src/integration/grep-path-matrix.test.ts +4 -3
  30. package/src/integration/grep-regex.test.ts +13 -16
  31. package/src/integration/grep-rg.test.ts +132 -92
  32. package/src/integration/grep-scan-budget.test.ts +27 -5
  33. package/src/integration/large-text.test.ts +4 -5
  34. package/src/integration/model-budget-lifecycle.test.ts +26 -8
  35. package/src/integration/mutation-file-types.test.ts +0 -1
  36. package/src/integration/mutation-file-types.testing.ts +2 -2
  37. package/src/integration/npm-package.testing.ts +7 -33
  38. package/src/integration/publication-read-changes.test.ts +60 -28
  39. package/src/integration/replace-package.testing.ts +4 -1
  40. package/src/integration/replace-worker-boundary.test.ts +34 -24
  41. package/src/integration/report-replay.test.ts +3 -3
  42. package/src/integration/utf8-errors.test.ts +3 -3
  43. package/src/pi/AGENTS.md +13 -14
  44. package/src/pi/action-fusion.test.ts +75 -220
  45. package/src/pi/action-fusion.ts +37 -74
  46. package/src/pi/anchor-format.test.ts +16 -0
  47. package/src/pi/anchor-format.ts +7 -3
  48. package/src/pi/argument-diagnostics.ts +35 -186
  49. package/src/pi/argument-error.testing.ts +7 -4
  50. package/src/pi/argument-error.ts +5 -7
  51. package/src/pi/argument-format.test.ts +25 -38
  52. package/src/pi/argument-validation.test.ts +446 -420
  53. package/src/pi/argument-validation.ts +4 -5
  54. package/src/pi/budgets.ts +5 -7
  55. package/src/pi/config.test.ts +15 -5
  56. package/src/pi/config.ts +6 -6
  57. package/src/pi/diagnostic-buffer.test.ts +2 -3
  58. package/src/pi/diagnostic-buffer.ts +2 -2
  59. package/src/pi/edit-tool.ts +175 -121
  60. package/src/pi/execute.test.ts +170 -227
  61. package/src/pi/failure-context.test.ts +61 -16
  62. package/src/pi/failure-context.ts +13 -10
  63. package/src/pi/failure-path.test.ts +115 -50
  64. package/src/pi/file-commit.test.ts +30 -46
  65. package/src/pi/file-commit.ts +11 -40
  66. package/src/pi/file-revision.ts +25 -0
  67. package/src/pi/fusion-card-interaction.test.ts +143 -0
  68. package/src/pi/fusion-card.test.ts +193 -37
  69. package/src/pi/fusion-card.ts +186 -116
  70. package/src/pi/grep-candidates.ts +25 -27
  71. package/src/pi/grep-matrix.test.ts +1 -1
  72. package/src/pi/grep-order.test.ts +323 -0
  73. package/src/pi/grep-output.testing.ts +24 -0
  74. package/src/pi/grep-output.ts +62 -69
  75. package/src/pi/grep-render.ts +4 -1
  76. package/src/pi/grep-scope.ts +1 -1
  77. package/src/pi/grep-search.ts +85 -56
  78. package/src/pi/grep-tool.ts +17 -48
  79. package/src/pi/grep.test.ts +271 -170
  80. package/src/pi/mutation-outcome.testing.ts +2 -3
  81. package/src/pi/mutation-result.test.ts +26 -19
  82. package/src/pi/mutation-result.ts +25 -40
  83. package/src/pi/mutation-runner.ts +9 -17
  84. package/src/pi/output-budgets.test.ts +27 -18
  85. package/src/pi/path.ts +3 -1
  86. package/src/pi/pi.test.ts +7 -6
  87. package/src/pi/read-tool.ts +32 -80
  88. package/src/pi/read.test.ts +145 -92
  89. package/src/pi/regex-worker-contract.ts +5 -23
  90. package/src/pi/regex-worker.ts +4 -10
  91. package/src/pi/registration.test.ts +106 -67
  92. package/src/pi/render.test.ts +239 -109
  93. package/src/pi/render.ts +42 -22
  94. package/src/pi/replace-regex.ts +3 -5
  95. package/src/pi/replace-tool.ts +29 -27
  96. package/src/pi/replace-worker-contract.ts +3 -12
  97. package/src/pi/replace.test.ts +144 -226
  98. package/src/pi/report-cause.ts +23 -19
  99. package/src/pi/report-failure.testing.ts +2 -2
  100. package/src/pi/report-schema.ts +60 -45
  101. package/src/pi/report.test.ts +138 -71
  102. package/src/pi/report.ts +40 -43
  103. package/src/pi/result-safety.test.ts +186 -131
  104. package/src/pi/rg-process.test.ts +36 -10
  105. package/src/pi/rg-process.ts +9 -3
  106. package/src/pi/rg-regex.test.ts +17 -0
  107. package/src/pi/rg-regex.ts +28 -22
  108. package/src/pi/text-stream.test.ts +35 -36
  109. package/src/pi/text-stream.ts +14 -14
  110. package/src/pi/tool-call.testing.ts +17 -7
  111. package/src/pi/write-tool.ts +9 -11
  112. package/src/pi/write.test.ts +43 -75
  113. package/src/testing/regex-translation-corpus.ts +16 -0
  114. package/src/testing/rg-line-listing.fixture.mjs +1 -1
  115. package/src/integration/forget-grep.test.ts +0 -148
  116. package/src/pi/forget-tool.ts +0 -367
  117. package/src/pi/forget.test.ts +0 -630
  118. package/src/pi/forget.testing.ts +0 -201
@@ -25,26 +25,20 @@ import { Text } from "@earendil-works/pi-tui";
25
25
  import { Type } from "typebox";
26
26
  import { scanTextLines } from "./text-stream.ts";
27
27
  import { createAnchorFormatter, displayCarriageReturns, parseHashline } from "./anchor-format.ts";
28
- import { canonicalPath } from "./path.ts";
29
- import { renderToolError, reportLines, withoutReport } from "./render.ts";
30
- import { type ForgetReceiptDetails, readReceipt, withResultTag } from "./forget-tool.ts";
28
+ import { canonicalPath, serializePath } from "./path.ts";
29
+ import { renderToolError, reportLines, splitReport } from "./render.ts";
31
30
  import { POSITIVE_SAFE_INTEGER } from "./schema.ts";
32
31
  import { errnoCode } from "../core/errors.ts";
33
32
  import { throwIfCancelled } from "./error-text.ts";
34
- import { runTool, type Report, type ReportDetails } from "./report.ts";
35
- import { defaultOutputBudgets, formatKiB, type OutputBudgetProvider } from "./budgets.ts";
33
+ import { reportResult, runTool, type ReportDetails } from "./report.ts";
34
+ import { defaultOutputBudgets, formatByteSize, type OutputBudgetProvider } from "./budgets.ts";
36
35
  import type { HashlineEditConfig } from "./config.ts";
37
36
  import { createArgumentPreparer } from "./argument-validation.ts";
38
37
 
39
38
  const DEFAULT_OFFSET = 1;
40
39
 
41
- type ReadDetails = ReadToolDetails & {
42
- nativeRead?: true;
43
- pagination?: NonNullable<Report["pagination"]>;
44
- } & ForgetReceiptDetails &
45
- Partial<ReportDetails>;
46
- /** The read card shows the forget id only on the forget card. */
47
- const READ_CARD_SHOWN = new Set(["resultId"]);
40
+ /** Pi's read details for a delegated native read; the report states this read's own facts. */
41
+ type ReadDetails = (ReadToolDetails & { nativeRead?: true }) & Partial<ReportDetails>;
48
42
 
49
43
  /**
50
44
  * First result line: `<path> · <N> lines`, optionally ` (from line <offset>)` and
@@ -61,7 +55,7 @@ function formatReadHeader(
61
55
  const shownFrom = start > DEFAULT_OFFSET ? ` (from line ${start})` : "";
62
56
  return `${path} · ${totalLines} lines${shownFrom}${finalNewline ? "" : " · no trailing newline"}`;
63
57
  }
64
- const READ_HEADER = /^(.+?) · (\d+ lines(?: \(from line \d+\))?(?: · no trailing newline)?)$/;
58
+ const READ_HEADER = /^(.+?) · (\d+ lines(?: \(from line \d+\))?(?: · no trailing newline)?)$/s;
65
59
 
66
60
  /**
67
61
  * Render the expanded read body for the TUI: color the header, strip the
@@ -149,7 +143,7 @@ export function makeReadOverride(
149
143
  name: "read" as const,
150
144
  label: "read",
151
145
  description:
152
- "Read a file. Text lines show as LINE#HASH│content anchors for edit; CRLF line endings show as LF. Use read, not shell output, for files you will edit.",
146
+ "Read a file. Text lines show as LINE#HASH│content anchors for edit; CRLF line endings show as LF.",
153
147
  promptSnippet: "Read files with editable line anchors",
154
148
  parameters: parameters as typeof builtin.parameters,
155
149
  prepareArguments: createArgumentPreparer("read", parameters, undefined, budgets),
@@ -160,19 +154,18 @@ export function makeReadOverride(
160
154
  renderResult(result, options, theme, context) {
161
155
  const { isPartial, expanded } = options;
162
156
  if (isPartial) return new Text(theme.fg("warning", "Reading…"), 0, 0);
163
- if (context?.isError) return renderToolError(result, theme, expanded);
157
+ if (context?.isError) return renderToolError(result, "read", theme, expanded);
158
+ const { content, report } = splitReport(result);
164
159
  if (result.details?.nativeRead)
165
- return builtin.renderResult!(withoutReport(result), options, theme, context);
160
+ return builtin.renderResult!({ ...result, content }, options, theme, context);
166
161
  // Collapsed (not expanded): show nothing — the call line carries the
167
162
  // title, matching the built-in read's fold behavior.
168
163
  if (!expanded) return new Text("", 0, 0);
169
- const content = withoutReport(result).content[0];
170
- const raw = content?.type === "text" ? content.text : "";
171
- const report = result.details?.report;
164
+ const raw = content[0]?.type === "text" ? content[0].text : "";
172
165
  return new Text(
173
166
  [
174
167
  renderReadBody(raw, String(context?.args?.path ?? ""), theme),
175
- ...(report ? reportLines(report, theme, READ_CARD_SHOWN) : []),
168
+ ...(report ? reportLines(report, theme) : []),
176
169
  ].join("\n"),
177
170
  0,
178
171
  0,
@@ -197,22 +190,10 @@ export function makeReadOverride(
197
190
  const report = { tool: "read" as const, path: params.path };
198
191
  const readNative = async () => {
199
192
  const result = await builtin.execute(toolCallId, params, signal, onUpdate, ctx);
200
- return withResultTag(
201
- toolCallId,
202
- {
203
- report,
204
- payload: result.content,
205
- details: { ...result.details, nativeRead: true as const },
206
- },
207
- config.forget,
208
- () =>
209
- readReceipt(
210
- params.path,
211
- result.content.some((block) => block.type === "image")
212
- ? { image: true }
213
- : undefined,
214
- ),
215
- );
193
+ return reportResult(report, result.content, {
194
+ ...result.details,
195
+ nativeRead: true as const,
196
+ });
216
197
  };
217
198
 
218
199
  const absPath = canonicalPath(cwd, params.path);
@@ -226,8 +207,6 @@ export function makeReadOverride(
226
207
 
227
208
  const rows: string[] = [];
228
209
  const crExpansion = Buffer.byteLength(displayCarriageReturns("\r")) - 1;
229
- let totalRows = 0;
230
- let totalBytes = 0;
231
210
  let outputBytes = 0;
232
211
  let truncated = false;
233
212
  let firstLineExceedsLimit = false;
@@ -237,12 +216,11 @@ export function makeReadOverride(
237
216
  absPath,
238
217
  (number) => number >= start && number - start < limit,
239
218
  (line) => {
219
+ if (truncated) return;
240
220
  const rowBytes =
241
221
  line.byteLength +
242
222
  line.carriageReturns * crExpansion +
243
223
  Buffer.byteLength(anchors.row(line.number, ""));
244
- totalBytes += rowBytes + (totalRows++ > 0 ? 1 : 0);
245
- if (truncated) return;
246
224
  const nextBytes = outputBytes + rowBytes + (rows.length > 0 ? 1 : 0);
247
225
  if (nextBytes > maxBytes) {
248
226
  truncated = true;
@@ -262,9 +240,13 @@ export function makeReadOverride(
262
240
  throw error;
263
241
  }
264
242
  if (stats.hasNul) return readNative();
265
- // Rows were returned and more remain, whether the line limit or the byte budget stopped them.
243
+ // Rows were returned and more remain. A caller's own limit is a chosen window: its header
244
+ // and rows already show where it ends, so only a window the extension cut (default limit
245
+ // or byte budget) gets a report.
266
246
  const pagination =
267
- rows.length > 0 && start + rows.length <= stats.totalLines
247
+ (params.limit === undefined || truncated) &&
248
+ rows.length > 0 &&
249
+ start + rows.length <= stats.totalLines
268
250
  ? {
269
251
  start,
270
252
  end: start + (rows.length - 1),
@@ -272,47 +254,17 @@ export function makeReadOverride(
272
254
  nextOffset: start + rows.length,
273
255
  }
274
256
  : undefined;
275
- // Pi's ReadToolDetails truncation shape; this read stops only at the byte limit.
276
- const truncation = {
277
- content: rows.join("\n"),
278
- truncated,
279
- truncatedBy: truncated ? ("bytes" as const) : null,
280
- totalLines: totalRows,
281
- totalBytes,
282
- outputLines: rows.length,
283
- outputBytes,
284
- lastLinePartial: false,
285
- firstLineExceedsLimit,
286
- maxLines: totalRows,
287
- maxBytes,
288
- };
289
-
290
- const header = `${formatReadHeader(params.path, stats.totalLines, start, stats.finalNewline)}\n`;
291
- const limitText = formatKiB(maxBytes);
257
+ const header = `${formatReadHeader(serializePath(cwd, absPath), stats.totalLines, start, stats.finalNewline)}\n`;
258
+ const limitText = formatByteSize(maxBytes);
292
259
 
293
- return withResultTag(
294
- toolCallId,
260
+ return reportResult(
295
261
  {
296
- report: {
297
- ...report,
298
- pagination,
299
- truncatedAt: truncated && !firstLineExceedsLimit ? limitText : undefined,
300
- lineTooLong: firstLineExceedsLimit ? { line: start, limit: limitText } : undefined,
301
- },
302
- payload: [{ type: "text" as const, text: header + truncation.content }],
303
- details: {
304
- ...(truncated ? { truncation } : {}),
305
- ...(pagination ? { pagination } : {}),
306
- },
262
+ ...report,
263
+ pagination,
264
+ outputLimit: truncated && !firstLineExceedsLimit ? limitText : undefined,
265
+ lineTooLong: firstLineExceedsLimit ? { line: start, limit: limitText } : undefined,
307
266
  },
308
- config.forget,
309
- () =>
310
- readReceipt(
311
- params.path,
312
- rows.length > 0
313
- ? { start, end: start + rows.length - 1, truncated: truncation.truncated }
314
- : undefined,
315
- ),
267
+ [{ type: "text" as const, text: header + rows.join("\n") }],
316
268
  );
317
269
  });
318
270
  },
@@ -1,7 +1,7 @@
1
1
  import { rejectsArgument, rejectsArguments } from "./argument-error.testing.ts";
2
2
  import { test } from "node:test";
3
3
  import assert from "node:assert/strict";
4
- import { mkdtemp, rm, readFile, writeFile } from "node:fs/promises";
4
+ import { mkdir, mkdtemp, rm, readFile, writeFile } from "node:fs/promises";
5
5
  import { tmpdir } from "node:os";
6
6
  import { join } from "node:path";
7
7
  import { initTheme } from "@earendil-works/pi-coding-agent";
@@ -11,9 +11,9 @@ import { makeReadOverride } from "./read-tool.ts";
11
11
  import { computeLineHash } from "../core/hash.ts";
12
12
  import { callTool } from "./tool-call.testing.ts";
13
13
  import { DEFAULT_CONFIG } from "./config.ts";
14
- import { DEFAULT_OUTPUT_BUDGETS, FORGET_MIN_BYTES, formatKiB } from "./budgets.ts";
15
- import { taggedResultId } from "./forget.testing.ts";
14
+ import { DEFAULT_OUTPUT_BUDGETS, formatByteSize } from "./budgets.ts";
16
15
  import { reportOf } from "./report.ts";
16
+ import { createAnchorFormatter } from "./anchor-format.ts";
17
17
 
18
18
  const DEFAULT_READ_MAX_BYTES = DEFAULT_OUTPUT_BUDGETS.readBytes;
19
19
 
@@ -36,7 +36,7 @@ initTheme();
36
36
  test("read execute: text outputs LINE#HASH│content", async () => {
37
37
  await withDir(async (dir) => {
38
38
  await writeFile(join(dir, "f.txt"), "line1\nline2\n");
39
- const r: any = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "f.txt" });
39
+ const r = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "f.txt" });
40
40
  const text = r.content[0];
41
41
  assert.equal(text.type, "text");
42
42
  assert.match(text.text, /1#[0-9A-Z]+│line1/);
@@ -45,6 +45,35 @@ test("read execute: text outputs LINE#HASH│content", async () => {
45
45
  });
46
46
  });
47
47
 
48
+ test("absolute path inside cwd → read header uses relative spelling", async () =>
49
+ withDir(async (dir) => {
50
+ const path = join(dir, "f.txt");
51
+ await writeFile(path, "line1\nline2\n");
52
+ const result = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path });
53
+ assert.equal(result.isError, undefined);
54
+ assert.equal(result.content[0].text.split("\n")[0], "f.txt · 2 lines");
55
+ }));
56
+
57
+ test(
58
+ "Windows absolute path outside cwd → read header uses forward slashes",
59
+ {
60
+ skip: process.platform !== "win32",
61
+ },
62
+ async () =>
63
+ withDir(async (dir) => {
64
+ const cwd = join(dir, "workspace");
65
+ await mkdir(cwd);
66
+ const path = join(dir, "outside.txt");
67
+ await writeFile(path, "line1\nline2\n");
68
+ const result = await call(makeReadOverride(cwd, DEFAULT_CONFIG), { path });
69
+ assert.equal(result.isError, undefined);
70
+ assert.equal(
71
+ result.content[0].text.split("\n")[0],
72
+ `${path.replaceAll("\\", "/")} · 2 lines`,
73
+ );
74
+ }),
75
+ );
76
+
48
77
  test("read execute: Pi-supported images without NUL bypass text decoding", async () =>
49
78
  withDir(async (dir) => {
50
79
  for (const [name, bytes, mime] of [
@@ -76,9 +105,18 @@ test("hash length stays 4 even for runs of identical lines (no explosion)", asyn
76
105
  await writeFile(f, "\n\n\n\ncode\n");
77
106
  const r: any = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "f.txt" });
78
107
  const text: string = r.content[0].text;
79
- for (const m of text.matchAll(/\d+#([0-9A-Z]+)│/g)) {
80
- assert.equal(m[1].length, 4, `anchor ${m[0]} hash is not 4 chars`);
81
- }
108
+ const rows = [...text.matchAll(/^(\d+)#([0-9A-Z]+)│(.*)$/gm)];
109
+ assert.deepEqual(
110
+ rows.map((row) => [Number(row[1]), row[3]]),
111
+ [
112
+ [1, ""],
113
+ [2, ""],
114
+ [3, ""],
115
+ [4, ""],
116
+ [5, "code"],
117
+ ],
118
+ );
119
+ for (const row of rows) assert.equal(row[2].length, DEFAULT_CONFIG.hashLen);
82
120
  });
83
121
  });
84
122
 
@@ -91,10 +129,7 @@ test("read byte truncation counts UTF-8 and separators without cutting anchors",
91
129
  const second = "x".repeat(maxBytes - Buffer.byteLength(first) - 2 * prefixBytes);
92
130
  await writeFile(join(dir, "large.txt"), `${first}\n${second}\n`);
93
131
  const result = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "large.txt" });
94
- assert.equal(result.details.truncation.outputLines, 1);
95
- assert.equal(result.details.truncation.truncatedBy, "bytes");
96
- assert.equal(result.details.truncation.maxBytes, maxBytes);
97
- assert.equal(reportOf(result)?.truncatedAt, formatKiB(maxBytes));
132
+ assert.equal(reportOf(result, "read")?.outputLimit, formatByteSize(maxBytes));
98
133
  assert.ok(result.content[0].text.includes(`1#${computeLineHash(1, first, hashLen)}│${first}`));
99
134
  assert.doesNotMatch(result.content[0].text, /\n2#/);
100
135
  const next = await call(makeReadOverride(dir, DEFAULT_CONFIG), {
@@ -109,12 +144,13 @@ test("read reports an oversized first row without suggesting an ineffective retr
109
144
  withDir(async (dir) => {
110
145
  await writeFile(join(dir, "long.txt"), "x".repeat(DEFAULT_READ_MAX_BYTES));
111
146
  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
147
  assert.doesNotMatch(result.content[0].text, /^\d+#/m);
115
148
  assert.doesNotMatch(result.content[0].text, /use offset\/limit/);
116
- assert.equal(reportOf(result)?.lineTooLong?.line, 1);
117
- assert.match(reportOf(result)?.next ?? "", /chunks.*bash.*replace/);
149
+ assert.deepEqual(reportOf(result, "read")?.lineTooLong, {
150
+ line: 1,
151
+ limit: formatByteSize(DEFAULT_READ_MAX_BYTES),
152
+ });
153
+ assert.match(reportOf(result, "read")?.next ?? "", /chunks.*bash.*replace/);
118
154
  }));
119
155
 
120
156
  test("read preserves empty files and explicit limits above the native default", async () =>
@@ -122,17 +158,17 @@ test("read preserves empty files and explicit limits above the native default",
122
158
  await writeFile(join(dir, "empty.txt"), "");
123
159
  const empty = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "empty.txt" });
124
160
  assert.match(empty.content[0].text, /0 lines/);
125
- assert.equal(reportOf(empty)?.pagination, undefined);
161
+ assert.equal(reportOf(empty, "read")?.pagination, undefined);
126
162
  await writeFile(join(dir, "many.txt"), "x\n".repeat(2001));
127
163
  const many = await call(makeReadOverride(dir, DEFAULT_CONFIG), {
128
164
  path: "many.txt",
129
165
  limit: 2001,
130
166
  });
131
167
  assert.match(many.content[0].text, /\n2001#[0-9A-Z]+│x/);
132
- assert.equal(reportOf(many)?.pagination, undefined);
168
+ assert.equal(reportOf(many, "read")?.pagination, undefined);
133
169
  }));
134
170
 
135
- test("read uses the configured default limit and respects explicit limits", async () =>
171
+ test("read window end chosen by caller or default → only the default offers optional continuation", async () =>
136
172
  withDir(async (dir) => {
137
173
  const defaultLimit = DEFAULT_CONFIG.read.defaultLimit;
138
174
  const totalLines = defaultLimit + 100;
@@ -140,7 +176,7 @@ test("read uses the configured default limit and respects explicit limits", asyn
140
176
  join(dir, "large.txt"),
141
177
  Array.from({ length: totalLines }, (_, i) => `line${i + 1}\n`).join(""),
142
178
  );
143
- for (const limit of [undefined, defaultLimit + 50]) {
179
+ for (const limit of [undefined, defaultLimit, defaultLimit + 50]) {
144
180
  const result = await call(makeReadOverride(dir, DEFAULT_CONFIG), {
145
181
  path: "large.txt",
146
182
  limit,
@@ -149,13 +185,16 @@ test("read uses the configured default limit and respects explicit limits", asyn
149
185
  assert.match(result.content[0].text, new RegExp(`large\\.txt · ${totalLines} lines`));
150
186
  assert.match(result.content[0].text, new RegExp(`\\n${end}#[0-9A-Z]+│line${end}`));
151
187
  assert.doesNotMatch(result.content[0].text, new RegExp(`\\n${end + 1}#[0-9A-Z]+│`));
152
- assert.deepEqual(reportOf(result)?.pagination, {
153
- start: 1,
154
- end,
155
- totalLines,
156
- nextOffset: end + 1,
157
- });
158
- assert.match(reportOf(result)?.next ?? "", /offset.*pagination\.nextOffset/);
188
+ const pagination = { start: 1, end, totalLines, nextOffset: end + 1 };
189
+ const report = reportOf(result, "read");
190
+ assert.ok(report);
191
+ if (limit === undefined) {
192
+ assert.deepEqual(report.pagination, pagination);
193
+ assert.match(report.next ?? "", /if you need more lines.*offset.*pagination\.nextOffset/i);
194
+ } else {
195
+ assert.equal(Object.hasOwn(report, "pagination"), false);
196
+ assert.equal(Object.hasOwn(report, "next"), false);
197
+ }
159
198
  }
160
199
  }));
161
200
 
@@ -170,20 +209,27 @@ test("read pagination supports offset windows and stops suggesting continuation
170
209
  );
171
210
  const read = makeReadOverride(dir, DEFAULT_CONFIG);
172
211
  const page = await call(read, { path: "pages.txt", offset: start });
173
- assert.match(reportOf(page)?.next ?? "", /offset.*pagination\.nextOffset/);
174
- assert.deepEqual(reportOf(page)?.pagination, { start, end, totalLines, nextOffset: end + 1 });
212
+ assert.match(reportOf(page, "read")?.next ?? "", /offset.*pagination\.nextOffset/);
213
+ assert.deepEqual(reportOf(page, "read")?.pagination, {
214
+ start,
215
+ end,
216
+ totalLines,
217
+ nextOffset: end + 1,
218
+ });
219
+ const pagination = reportOf(page, "read")?.pagination;
220
+ assert.ok(pagination);
175
221
  const next = await call(read, {
176
222
  path: "pages.txt",
177
- offset: page.details.pagination.nextOffset,
223
+ offset: pagination.nextOffset,
178
224
  });
179
225
  assert.match(next.content[0].text, new RegExp(`\\n${end + 1}#[0-9A-Z]+│line${end + 1}`));
180
226
  assert.match(next.content[0].text, new RegExp(`\\n${totalLines}#[0-9A-Z]+│line${totalLines}`));
181
- assert.equal(reportOf(next)?.pagination, undefined);
182
- assert.equal(reportOf(next)?.next, undefined);
227
+ assert.equal(reportOf(next, "read")?.pagination, undefined);
228
+ assert.equal(reportOf(next, "read")?.next, undefined);
183
229
  for (const offset of [totalLines - DEFAULT_CONFIG.read.defaultLimit + 1, totalLines + 1]) {
184
230
  const result = await call(read, { path: "pages.txt", offset });
185
- assert.equal(reportOf(result)?.pagination, undefined);
186
- assert.equal(reportOf(result)?.next, undefined);
231
+ assert.equal(reportOf(result, "read")?.pagination, undefined);
232
+ assert.equal(reportOf(result, "read")?.next, undefined);
187
233
  }
188
234
  }));
189
235
 
@@ -220,24 +266,7 @@ test("read rejects noninteger and nonpositive offsets and limits before reading"
220
266
  }),
221
267
  { path: "pages.txt", offset: 2, limit: 550 },
222
268
  );
223
- await assert.rejects(
224
- call(read, { path: "missing.txt", offset: 1.5 }),
225
- rejectsArguments("read"),
226
- );
227
- const page = await call(read, { path: "pages.txt", offset: 2, limit: 1 });
228
- assert.match(page.content[0].text, /\n2#[0-9A-Z]+│second/);
229
- assert.match(reportOf(page)?.next ?? "", /offset.*pagination\.nextOffset/);
230
- assert.deepEqual(reportOf(page)?.pagination, {
231
- start: 2,
232
- end: 2,
233
- totalLines: 3,
234
- nextOffset: 3,
235
- });
236
- await writeFile(join(dir, "long.txt"), "x".repeat(DEFAULT_READ_MAX_BYTES + 1));
237
- const long = await call(read, { path: "long.txt", offset: 1, limit: 1 });
238
- assert.equal(long.details.truncation.firstLineExceedsLimit, true);
239
- assert.equal(long.details.truncation.outputLines, 0);
240
- assert.equal(long.details.truncation.maxBytes, DEFAULT_READ_MAX_BYTES);
269
+ await assert.rejects(call(read, { path: "missing.txt", offset: 1.5 }), rejectsArguments());
241
270
  }));
242
271
 
243
272
  test("read schema rejects empty paths and unknown fields before file access", async () =>
@@ -248,7 +277,7 @@ test("read schema rejects empty paths and unknown fields before file access", as
248
277
  { path: "missing.txt", offest: 3 },
249
278
  ];
250
279
  for (const args of invalidArgs) {
251
- await assert.rejects(call(read, args), rejectsArguments("read"));
280
+ await assert.rejects(call(read, args), rejectsArguments());
252
281
  }
253
282
  }));
254
283
 
@@ -259,18 +288,18 @@ test("read byte truncation retains its budget and a continuation after complete
259
288
  path: "large.txt",
260
289
  limit: 2,
261
290
  });
262
- assert.equal(result.details.truncation.truncatedBy, "bytes");
263
- assert.deepEqual(reportOf(result)?.pagination, {
291
+ assert.deepEqual(reportOf(result, "read")?.pagination, {
264
292
  start: 1,
265
293
  end: 1,
266
294
  totalLines: 3,
267
295
  nextOffset: 2,
268
296
  });
269
- assert.equal(result.details.truncation.maxBytes, DEFAULT_READ_MAX_BYTES);
297
+ assert.equal(reportOf(result, "read")?.outputLimit, formatByteSize(DEFAULT_READ_MAX_BYTES));
298
+ assert.match(reportOf(result, "read")?.next ?? "", /offset.*pagination\.nextOffset/);
270
299
  assert.doesNotMatch(result.content[0].text, /showing lines|to continue/);
271
300
  }));
272
301
 
273
- test("read bounds oversized selected lines while preserving truncation metadata and later anchors", async () =>
302
+ test("read bounds oversized selected lines while reporting limits and preserving later anchors", async () =>
274
303
  withDir(async (dir) => {
275
304
  const long = "界".repeat(200_000);
276
305
  await writeFile(join(dir, "long.txt"), `first\r\n${long}\r\nlast`);
@@ -278,15 +307,14 @@ test("read bounds oversized selected lines while preserving truncation metadata
278
307
  const result = await call(read, { path: "long.txt" });
279
308
  assert.match(result.content[0].text, /1#[0-9A-Z]+│first/);
280
309
  assert.doesNotMatch(result.content[0].text, /2#[0-9A-Z]+│/);
281
- assert.equal(result.details.truncation.firstLineExceedsLimit, false);
282
- assert.equal(result.details.truncation.outputLines, 1);
283
- const expectedRows = ["first", long, "last"].map(
284
- (text, index) => `${index + 1}#${computeLineHash(index + 1, text, 4)}│${text}`,
285
- );
286
- assert.equal(result.details.truncation.totalBytes, Buffer.byteLength(expectedRows.join("\n")));
310
+ assert.equal(reportOf(result, "read")?.lineTooLong, undefined);
311
+ assert.equal(reportOf(result, "read")?.outputLimit, formatByteSize(DEFAULT_READ_MAX_BYTES));
287
312
  const oversized = await call(read, { path: "long.txt", offset: 2, limit: 1 });
288
- assert.equal(oversized.details.truncation.firstLineExceedsLimit, true);
289
- assert.equal(oversized.details.truncation.outputBytes, 0);
313
+ assert.deepEqual(reportOf(oversized, "read")?.lineTooLong, {
314
+ line: 2,
315
+ limit: formatByteSize(DEFAULT_READ_MAX_BYTES),
316
+ });
317
+ assert.doesNotMatch(oversized.content[0].text, /^\d+#/m);
290
318
  const last = await call(read, { path: "long.txt", offset: 3, limit: 1 });
291
319
  assert.match(last.content[0].text, /3#[0-9A-Z]+│last/);
292
320
  assert.match(last.content[0].text, /no trailing newline/);
@@ -297,12 +325,11 @@ test("read budgets visible standalone CR characters using rendered UTF-8 bytes",
297
325
  const content = "\r".repeat(90_000);
298
326
  await writeFile(join(dir, "cr.txt"), content);
299
327
  const result = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "cr.txt", limit: 1 });
300
- assert.equal(result.details.truncation.firstLineExceedsLimit, true);
301
- assert.equal(result.details.truncation.outputBytes, 0);
302
- assert.equal(
303
- result.details.truncation.totalBytes,
304
- Buffer.byteLength(`1#${computeLineHash(1, content, 4)}│${"␍".repeat(content.length)}`),
305
- );
328
+ assert.deepEqual(reportOf(result, "read")?.lineTooLong, {
329
+ line: 1,
330
+ limit: formatByteSize(DEFAULT_READ_MAX_BYTES),
331
+ });
332
+ assert.doesNotMatch(result.content[0].text, /^\d+#/m);
306
333
  }));
307
334
 
308
335
  test("read renders native content without interpreting anchor-like prefixes", async () =>
@@ -336,32 +363,58 @@ test("read accepts safe offsets and limits whose sum exceeds the safe integer ra
336
363
  offset,
337
364
  limit: Number.MAX_SAFE_INTEGER,
338
365
  });
339
- assert.equal(reportOf(result)?.pagination, undefined);
366
+ assert.equal(reportOf(result, "read")?.pagination, undefined);
340
367
  assert.doesNotMatch(result.content[0].text, /to continue|│first/);
341
368
  if (offset <= 3) assert.match(result.content[0].text, /│third/);
342
369
  else assert.doesNotMatch(result.content[0].text, /│/);
343
370
  }
344
371
  }));
345
372
 
346
- test("read text reaches the forget byte threshold → only eligible results receive a tag", async () =>
347
- withDir(async (dir) => {
348
- const path = join(dir, "threshold.txt");
349
- const read = makeReadOverride(dir, { ...DEFAULT_CONFIG, forget: true });
350
- await writeFile(path, "界\n");
351
- const initial: Awaited<ReturnType<typeof read.execute>> = await callTool(read, { path });
352
- const initialBlock = initial.content[0];
353
- assert.ok(initialBlock.type === "text");
354
- const initialBytes = Buffer.byteLength(initialBlock.text);
355
- for (const bytes of [FORGET_MIN_BYTES - 1, FORGET_MIN_BYTES, FORGET_MIN_BYTES + 1]) {
356
- await writeFile(path, `界${"x".repeat(bytes - initialBytes)}\n`);
357
- const result: Awaited<ReturnType<typeof read.execute>> = await callTool(
358
- read,
359
- { path },
360
- { toolCallId: `read-${bytes}` },
361
- );
362
- const body = result.content[0];
363
- assert.ok(body.type === "text");
364
- assert.equal(Buffer.byteLength(body.text), bytes);
365
- assert.equal(taggedResultId(result) !== undefined, bytes >= FORGET_MIN_BYTES);
373
+ test("Unicode line separators in a read path or middle row → renders every following row", async (t) => {
374
+ const tool = makeReadOverride(process.cwd(), DEFAULT_CONFIG);
375
+ const render = tool.renderResult;
376
+ assert.ok(render);
377
+ const formatter = createAnchorFormatter(DEFAULT_CONFIG.hashLen);
378
+ for (const separator of ["\u2028", "\u2029"]) {
379
+ for (const location of ["path", "middle row"]) {
380
+ await t.test(`${location} ${JSON.stringify(separator)}`, () => {
381
+ const path = location === "path" ? `before${separator}after.txt` : "read.txt";
382
+ const lines = [
383
+ "first",
384
+ location === "middle row" ? `before${separator}after` : "middle",
385
+ "third",
386
+ "last",
387
+ ];
388
+ const header = `${path} · ${lines.length} lines`;
389
+ const raw = [header, ...lines.map((line, index) => formatter.row(index + 1, line))].join(
390
+ "\n",
391
+ );
392
+ const rendered = render(
393
+ { content: [{ type: "text", text: raw }], details: undefined },
394
+ { expanded: true, isPartial: false },
395
+ stubTheme,
396
+ {
397
+ args: { path },
398
+ state: {},
399
+ cwd: process.cwd(),
400
+ toolCallId: "unicode-read",
401
+ lastComponent: undefined,
402
+ invalidate() {},
403
+ executionStarted: true,
404
+ argsComplete: true,
405
+ isPartial: false,
406
+ expanded: true,
407
+ showImages: false,
408
+ isError: false,
409
+ },
410
+ )
411
+ .render(120)
412
+ .map((line) => line.trimEnd());
413
+ assert.deepEqual(rendered, [
414
+ header,
415
+ ...lines.map((line, index) => ` ${index + 1}: ${line}`),
416
+ ]);
417
+ });
366
418
  }
367
- }));
419
+ }
420
+ });
@@ -1,19 +1,9 @@
1
1
  /** Closed reply envelopes shared by isolated regex evaluators; decoded in the host. */
2
2
  import { Type, type Static, type TSchema } from "typebox";
3
3
  import { Value } from "typebox/value";
4
- import {
5
- HashlineError,
6
- type HashlineErrorArguments,
7
- type HashlineErrorOptions,
8
- } from "../core/errors.ts";
9
- import {
10
- ERROR_CODES,
11
- ERROR_DEFINITIONS,
12
- CAUSE_SCHEMA,
13
- type ErrorCode,
14
- type Cause,
15
- } from "./report-schema.ts";
16
- import { restoreCause } from "./report-cause.ts";
4
+ import { HashlineError, type HashlineErrorArguments } from "../core/errors.ts";
5
+ import { ERROR_CODES, ERROR_DEFINITIONS, CAUSE_SCHEMA, type ErrorCode } from "./report-schema.ts";
6
+ import { restoreCause, type WorkerError } from "./report-cause.ts";
17
7
 
18
8
  const ERROR_SCHEMAS = ERROR_CODES.map((code) => {
19
9
  const facts = ERROR_DEFINITIONS[code].facts;
@@ -27,17 +17,9 @@ const ERROR_SCHEMAS = ERROR_CODES.map((code) => {
27
17
  { additionalProperties: false },
28
18
  );
29
19
  });
30
- /** A worker error that passed its code's schema: the facts are those that code requires. */
31
- export type CheckedWorkerError = {
32
- [C in ErrorCode]: {
33
- readonly code: C;
34
- readonly message: string;
35
- readonly cause?: Cause;
36
- } & Pick<HashlineErrorOptions<C>, "facts">;
37
- }[ErrorCode];
38
20
  export type RegexWorkerReply<Result> =
39
21
  | { readonly result: Result }
40
- | { readonly error: CheckedWorkerError };
22
+ | { readonly error: WorkerError };
41
23
 
42
24
  export function invalidWorkerResult(): HashlineError<"REGEX_WORKER_FAILED"> {
43
25
  return new HashlineError("REGEX_WORKER_FAILED", "Regex worker returned an invalid result.");
@@ -64,7 +46,7 @@ export function workerReplyDecoder<T extends TSchema>(result: T) {
64
46
  }
65
47
 
66
48
  /** Restore an error workerReplyDecoder checked as the same HashlineError the worker threw. */
67
- export function restoreWorkerError(error: CheckedWorkerError): HashlineError {
49
+ export function restoreWorkerError(error: WorkerError): HashlineError {
68
50
  // The parameter ties facts to code; TypeScript cannot carry that link into the generic constructor.
69
51
  const options = [
70
52
  { facts: error.facts, cause: restoreCause(error.cause) },