@criogaid/pi-hashline-edit 0.6.1 → 0.8.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 (161) hide show
  1. package/README.md +78 -369
  2. package/README.zh-CN.md +162 -0
  3. package/THIRD_PARTY_NOTICES.md +80 -0
  4. package/package.json +11 -6
  5. package/src/core/AGENTS.md +20 -0
  6. package/src/core/apply.test.ts +328 -161
  7. package/src/core/apply.ts +129 -95
  8. package/src/core/case-fold.test.ts +44 -0
  9. package/src/core/case-fold.ts +77 -0
  10. package/src/core/character-set.test.ts +103 -0
  11. package/src/core/character-set.ts +184 -0
  12. package/src/core/errors.test.ts +23 -0
  13. package/src/core/errors.ts +70 -4
  14. package/src/core/hash.test.ts +1 -25
  15. package/src/core/hash.ts +0 -5
  16. package/src/core/lines.ts +32 -7
  17. package/src/core/ranges.test.ts +41 -9
  18. package/src/core/ranges.ts +11 -4
  19. package/src/core/regex.ts +51 -0
  20. package/src/core/replace-schema.ts +41 -0
  21. package/src/core/replace.test.ts +90 -0
  22. package/src/core/replace.ts +40 -56
  23. package/src/core/search-analysis.test.ts +208 -0
  24. package/src/core/search-analysis.ts +379 -0
  25. package/src/core/search-matrix.test.ts +64 -0
  26. package/src/core/search-matrix.testing.ts +183 -0
  27. package/src/core/search-schema.ts +18 -0
  28. package/src/core/search.test.ts +145 -0
  29. package/src/core/search.ts +119 -0
  30. package/src/core/text.test.ts +16 -8
  31. package/src/core/text.ts +26 -6
  32. package/src/core/types.ts +20 -17
  33. package/src/index.ts +24 -16
  34. package/src/integration/config-registration.test.ts +42 -28
  35. package/src/integration/fusion-dispatch.test.ts +62 -127
  36. package/src/integration/grep-errors.test.ts +50 -0
  37. package/src/integration/grep-flags.test.ts +273 -0
  38. package/src/integration/grep-js-completeness.test.ts +218 -0
  39. package/src/integration/grep-line-candidates.test.ts +233 -0
  40. package/src/integration/grep-matrix.test.ts +121 -0
  41. package/src/integration/grep-order.test.ts +78 -0
  42. package/src/integration/grep-path-matrix.test.ts +133 -0
  43. package/src/integration/grep-prefilter-coverage.test.ts +189 -0
  44. package/src/integration/grep-regex.test.ts +407 -0
  45. package/src/integration/grep-rg.test.ts +294 -436
  46. package/src/integration/grep-scan-budget.test.ts +111 -0
  47. package/src/integration/grep-translation.test.ts +206 -0
  48. package/src/integration/large-text.test.ts +56 -1
  49. package/src/integration/model-budget-lifecycle.test.ts +137 -0
  50. package/src/integration/mutation-file-types.test.ts +12 -26
  51. package/src/integration/mutation-file-types.testing.ts +33 -0
  52. package/src/integration/npm-package.test.ts +17 -0
  53. package/src/integration/npm-package.testing.ts +97 -0
  54. package/src/integration/publication-read-changes.test.ts +376 -0
  55. package/src/integration/read-changes.test.ts +98 -0
  56. package/src/integration/replace-package.test.ts +17 -36
  57. package/src/integration/replace-package.testing.ts +36 -0
  58. package/src/integration/replace-worker-boundary.test.ts +117 -0
  59. package/src/integration/report-replay.test.ts +90 -0
  60. package/src/integration/utf8-errors.test.ts +46 -0
  61. package/src/pi/AGENTS.md +54 -0
  62. package/src/pi/action-fusion.test.ts +256 -251
  63. package/src/pi/action-fusion.ts +121 -332
  64. package/src/pi/anchor-format.test.ts +16 -0
  65. package/src/pi/anchor-format.ts +16 -3
  66. package/src/pi/argument-diagnostics.ts +478 -0
  67. package/src/pi/argument-error.testing.ts +46 -0
  68. package/src/pi/argument-error.ts +76 -0
  69. package/src/pi/argument-format.test.ts +197 -0
  70. package/src/pi/argument-validation.test.ts +780 -49
  71. package/src/pi/argument-validation.ts +55 -58
  72. package/src/pi/budgets.ts +48 -21
  73. package/src/pi/codemode.test.ts +96 -0
  74. package/src/pi/config.test.ts +29 -15
  75. package/src/pi/config.ts +27 -13
  76. package/src/pi/diagnostic-buffer.test.ts +51 -16
  77. package/src/pi/diagnostic-buffer.ts +13 -16
  78. package/src/pi/directory-sync.test.ts +4 -1
  79. package/src/pi/edit-tool.ts +103 -99
  80. package/src/pi/error-text.ts +39 -16
  81. package/src/pi/execute.test.ts +407 -429
  82. package/src/pi/extension-loading.test.ts +7 -27
  83. package/src/pi/extension-loading.testing.ts +2 -14
  84. package/src/pi/failure-context.test.ts +265 -88
  85. package/src/pi/failure-context.ts +165 -181
  86. package/src/pi/failure-path.test.ts +179 -117
  87. package/src/pi/file-commit.test.ts +90 -73
  88. package/src/pi/file-commit.ts +216 -178
  89. package/src/pi/file-read.test.ts +29 -0
  90. package/src/pi/file-read.ts +60 -0
  91. package/src/pi/file-revision.ts +25 -0
  92. package/src/pi/file-snapshot.test.ts +1 -1
  93. package/src/pi/fusion-card-interaction.test.ts +143 -0
  94. package/src/pi/fusion-card.test.ts +233 -51
  95. package/src/pi/fusion-card.ts +246 -142
  96. package/src/pi/grep-candidates.test.ts +127 -0
  97. package/src/pi/grep-candidates.ts +191 -0
  98. package/src/pi/grep-matrix.test.ts +83 -0
  99. package/src/pi/grep-order.test.ts +323 -0
  100. package/src/pi/grep-output.testing.ts +24 -0
  101. package/src/pi/grep-output.ts +187 -151
  102. package/src/pi/grep-render.ts +31 -25
  103. package/src/pi/grep-scope.ts +62 -54
  104. package/src/pi/grep-search.ts +327 -241
  105. package/src/pi/grep-tool.ts +126 -147
  106. package/src/pi/grep-worker.mjs +4 -0
  107. package/src/pi/grep-worker.ts +14 -0
  108. package/src/pi/grep.test.ts +813 -713
  109. package/src/pi/model-budgets.test.ts +43 -0
  110. package/src/pi/model-budgets.ts +44 -0
  111. package/src/pi/mutation-outcome.testing.ts +6 -7
  112. package/src/pi/mutation-result.test.ts +45 -91
  113. package/src/pi/mutation-result.ts +86 -114
  114. package/src/pi/mutation-runner.ts +81 -81
  115. package/src/pi/output-budgets.test.ts +175 -0
  116. package/src/pi/path.ts +10 -1
  117. package/src/pi/pi.test.ts +4 -5
  118. package/src/pi/read-tool.ts +108 -142
  119. package/src/pi/read.test.ts +155 -96
  120. package/src/pi/regex-worker-contract.ts +55 -0
  121. package/src/pi/regex-worker.ts +95 -0
  122. package/src/pi/registration.test.ts +148 -124
  123. package/src/pi/render.test.ts +361 -84
  124. package/src/pi/render.ts +150 -32
  125. package/src/pi/replace-regex.ts +13 -48
  126. package/src/pi/replace-tool.ts +52 -158
  127. package/src/pi/replace-worker-contract.ts +10 -0
  128. package/src/pi/replace-worker.ts +12 -8
  129. package/src/pi/replace.test.ts +191 -340
  130. package/src/pi/report-cause.ts +103 -0
  131. package/src/pi/report-failure.testing.ts +20 -0
  132. package/src/pi/report-schema.ts +524 -0
  133. package/src/pi/report.test.ts +343 -0
  134. package/src/pi/report.ts +285 -0
  135. package/src/pi/result-safety.test.ts +216 -481
  136. package/src/pi/rg-process.test.ts +101 -76
  137. package/src/pi/rg-process.ts +130 -177
  138. package/src/pi/rg-regex.test.ts +67 -0
  139. package/src/pi/rg-regex.ts +715 -0
  140. package/src/pi/text-stream.test.ts +97 -69
  141. package/src/pi/text-stream.ts +97 -76
  142. package/src/pi/tool-call.testing.ts +20 -46
  143. package/src/pi/write-tool.ts +50 -41
  144. package/src/pi/write.test.ts +71 -95
  145. package/src/testing/extension-loader.testing.ts +24 -0
  146. package/src/testing/installation.testing.ts +77 -0
  147. package/src/testing/process.testing.ts +33 -0
  148. package/src/testing/regex-host.testing.ts +20 -0
  149. package/src/testing/regex-translation-corpus.ts +324 -0
  150. package/src/testing/rg-line-listing.fixture.mjs +7 -0
  151. package/src/testing/run-tests.ts +47 -0
  152. package/src/testing/session.testing.ts +127 -0
  153. package/src/integration/forget-grep.test.ts +0 -98
  154. package/src/pi/forget-tool.ts +0 -268
  155. package/src/pi/forget.test.ts +0 -343
  156. package/src/pi/forget.testing.ts +0 -273
  157. package/src/pi/rg-line-ranges.test.ts +0 -66
  158. package/src/pi/rg-line-ranges.ts +0 -75
  159. package/src/pi/rg-match-bytes.ts +0 -95
  160. package/src/pi/rg-text-view.ts +0 -192
  161. package/src/pi/tool-prompts.ts +0 -15
@@ -1,6 +1,7 @@
1
+ import { rejectsArgument, rejectsArguments } from "./argument-error.testing.ts";
1
2
  import { test } from "node:test";
2
3
  import assert from "node:assert/strict";
3
- import { mkdtemp, rm, readFile, writeFile } from "node:fs/promises";
4
+ import { mkdir, mkdtemp, rm, readFile, writeFile } from "node:fs/promises";
4
5
  import { tmpdir } from "node:os";
5
6
  import { join } from "node:path";
6
7
  import { initTheme } from "@earendil-works/pi-coding-agent";
@@ -10,10 +11,11 @@ import { makeReadOverride } from "./read-tool.ts";
10
11
  import { computeLineHash } from "../core/hash.ts";
11
12
  import { callTool } from "./tool-call.testing.ts";
12
13
  import { DEFAULT_CONFIG } from "./config.ts";
13
- import { FORGET_MIN_BYTES, formatKiB } from "./budgets.ts";
14
- import { taggedResultId } from "./forget.testing.ts";
14
+ import { DEFAULT_OUTPUT_BUDGETS, formatByteSize } from "./budgets.ts";
15
+ import { reportOf } from "./report.ts";
16
+ import { createAnchorFormatter } from "./anchor-format.ts";
15
17
 
16
- const DEFAULT_READ_MAX_BYTES = DEFAULT_CONFIG.read.maxKiB * 1024;
18
+ const DEFAULT_READ_MAX_BYTES = DEFAULT_OUTPUT_BUDGETS.readBytes;
17
19
 
18
20
  async function withDir<T>(fn: (dir: string) => Promise<T>): Promise<T> {
19
21
  const dir = await mkdtemp(join(tmpdir(), "hl-"));
@@ -34,7 +36,7 @@ initTheme();
34
36
  test("read execute: text outputs LINE#HASH│content", async () => {
35
37
  await withDir(async (dir) => {
36
38
  await writeFile(join(dir, "f.txt"), "line1\nline2\n");
37
- const r: any = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "f.txt" });
39
+ const r = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "f.txt" });
38
40
  const text = r.content[0];
39
41
  assert.equal(text.type, "text");
40
42
  assert.match(text.text, /1#[0-9A-Z]+│line1/);
@@ -43,6 +45,35 @@ test("read execute: text outputs LINE#HASH│content", async () => {
43
45
  });
44
46
  });
45
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
+
46
77
  test("read execute: Pi-supported images without NUL bypass text decoding", async () =>
47
78
  withDir(async (dir) => {
48
79
  for (const [name, bytes, mime] of [
@@ -74,9 +105,18 @@ test("hash length stays 4 even for runs of identical lines (no explosion)", asyn
74
105
  await writeFile(f, "\n\n\n\ncode\n");
75
106
  const r: any = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "f.txt" });
76
107
  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
- }
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);
80
120
  });
81
121
  });
82
122
 
@@ -89,13 +129,8 @@ test("read byte truncation counts UTF-8 and separators without cutting anchors",
89
129
  const second = "x".repeat(maxBytes - Buffer.byteLength(first) - 2 * prefixBytes);
90
130
  await writeFile(join(dir, "large.txt"), `${first}\n${second}\n`);
91
131
  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
- );
132
+ assert.equal(reportOf(result, "read")?.outputLimit, formatByteSize(maxBytes));
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), {
101
136
  path: "large.txt",
@@ -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.match(result.content[0].text, /cannot split.*line/);
117
- assert.match(result.content[0].text, /bash.*chunks.*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(empty.details, 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(many.details, 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,10 +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(result.details, {
153
- pagination: { start: 1, end, totalLines, nextOffset: end + 1 },
154
- });
155
- assert.match(result.content[0].text, new RegExp(`offset ${end + 1}`));
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
+ }
156
198
  }
157
199
  }));
158
200
 
@@ -167,22 +209,27 @@ test("read pagination supports offset windows and stops suggesting continuation
167
209
  );
168
210
  const read = makeReadOverride(dir, DEFAULT_CONFIG);
169
211
  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 },
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,
173
218
  });
219
+ const pagination = reportOf(page, "read")?.pagination;
220
+ assert.ok(pagination);
174
221
  const next = await call(read, {
175
222
  path: "pages.txt",
176
- offset: page.details.pagination.nextOffset,
223
+ offset: pagination.nextOffset,
177
224
  });
178
225
  assert.match(next.content[0].text, new RegExp(`\\n${end + 1}#[0-9A-Z]+│line${end + 1}`));
179
226
  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/);
227
+ assert.equal(reportOf(next, "read")?.pagination, undefined);
228
+ assert.equal(reportOf(next, "read")?.next, undefined);
182
229
  for (const offset of [totalLines - DEFAULT_CONFIG.read.defaultLimit + 1, totalLines + 1]) {
183
230
  const result = await call(read, { path: "pages.txt", offset });
184
- assert.equal(result.details, undefined);
185
- assert.doesNotMatch(result.content[0].text, /to continue/);
231
+ assert.equal(reportOf(result, "read")?.pagination, undefined);
232
+ assert.equal(reportOf(result, "read")?.next, undefined);
186
233
  }
187
234
  }));
188
235
 
@@ -207,10 +254,7 @@ test("read rejects noninteger and nonpositive offsets and limits before reading"
207
254
  Number.MAX_SAFE_INTEGER + 1,
208
255
  ]) {
209
256
  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
- );
257
+ await assert.rejects(call(read, params), rejectsArgument(key));
214
258
  }
215
259
  }
216
260
  assert.deepEqual(
@@ -222,21 +266,7 @@ test("read rejects noninteger and nonpositive offsets and limits before reading"
222
266
  }),
223
267
  { path: "pages.txt", offset: 2, limit: 550 },
224
268
  );
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);
269
+ await assert.rejects(call(read, { path: "missing.txt", offset: 1.5 }), rejectsArguments());
240
270
  }));
241
271
 
242
272
  test("read schema rejects empty paths and unknown fields before file access", async () =>
@@ -247,24 +277,29 @@ test("read schema rejects empty paths and unknown fields before file access", as
247
277
  { path: "missing.txt", offest: 3 },
248
278
  ];
249
279
  for (const args of invalidArgs) {
250
- await assert.rejects(call(read, args), /Validation failed for tool "read"/);
280
+ await assert.rejects(call(read, args), rejectsArguments());
251
281
  }
252
282
  }));
253
283
 
254
- test("read byte truncation takes precedence over line pagination", async () =>
284
+ test("read byte truncation retains its budget and a continuation after complete returned rows", async () =>
255
285
  withDir(async (dir) => {
256
286
  await writeFile(join(dir, "large.txt"), `first\n${"x".repeat(DEFAULT_READ_MAX_BYTES)}\ntail\n`);
257
287
  const result = await call(makeReadOverride(dir, DEFAULT_CONFIG), {
258
288
  path: "large.txt",
259
289
  limit: 2,
260
290
  });
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);
291
+ assert.deepEqual(reportOf(result, "read")?.pagination, {
292
+ start: 1,
293
+ end: 1,
294
+ totalLines: 3,
295
+ nextOffset: 2,
296
+ });
297
+ assert.equal(reportOf(result, "read")?.outputLimit, formatByteSize(DEFAULT_READ_MAX_BYTES));
298
+ assert.match(reportOf(result, "read")?.next ?? "", /offset.*pagination\.nextOffset/);
264
299
  assert.doesNotMatch(result.content[0].text, /showing lines|to continue/);
265
300
  }));
266
301
 
267
- 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 () =>
268
303
  withDir(async (dir) => {
269
304
  const long = "界".repeat(200_000);
270
305
  await writeFile(join(dir, "long.txt"), `first\r\n${long}\r\nlast`);
@@ -272,15 +307,14 @@ test("read bounds oversized selected lines while preserving truncation metadata
272
307
  const result = await call(read, { path: "long.txt" });
273
308
  assert.match(result.content[0].text, /1#[0-9A-Z]+│first/);
274
309
  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")));
310
+ assert.equal(reportOf(result, "read")?.lineTooLong, undefined);
311
+ assert.equal(reportOf(result, "read")?.outputLimit, formatByteSize(DEFAULT_READ_MAX_BYTES));
281
312
  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);
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);
284
318
  const last = await call(read, { path: "long.txt", offset: 3, limit: 1 });
285
319
  assert.match(last.content[0].text, /3#[0-9A-Z]+│last/);
286
320
  assert.match(last.content[0].text, /no trailing newline/);
@@ -291,12 +325,11 @@ test("read budgets visible standalone CR characters using rendered UTF-8 bytes",
291
325
  const content = "\r".repeat(90_000);
292
326
  await writeFile(join(dir, "cr.txt"), content);
293
327
  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
- );
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);
300
333
  }));
301
334
 
302
335
  test("read renders native content without interpreting anchor-like prefixes", async () =>
@@ -330,32 +363,58 @@ test("read accepts safe offsets and limits whose sum exceeds the safe integer ra
330
363
  offset,
331
364
  limit: Number.MAX_SAFE_INTEGER,
332
365
  });
333
- assert.equal(result.details, undefined);
366
+ assert.equal(reportOf(result, "read")?.pagination, undefined);
334
367
  assert.doesNotMatch(result.content[0].text, /to continue|│first/);
335
368
  if (offset <= 3) assert.match(result.content[0].text, /│third/);
336
369
  else assert.doesNotMatch(result.content[0].text, /│/);
337
370
  }
338
371
  }));
339
372
 
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);
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
+ });
360
418
  }
361
- }));
419
+ }
420
+ });
@@ -0,0 +1,55 @@
1
+ /** Closed reply envelopes shared by isolated regex evaluators; decoded in the host. */
2
+ import { Type, type Static, type TSchema } from "typebox";
3
+ import { Value } from "typebox/value";
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";
7
+
8
+ const ERROR_SCHEMAS = ERROR_CODES.map((code) => {
9
+ const facts = ERROR_DEFINITIONS[code].facts;
10
+ return Type.Object(
11
+ {
12
+ code: Type.Literal(code),
13
+ message: Type.String(),
14
+ facts: (facts.required?.length ?? 0) > 0 ? facts : Type.Optional(facts),
15
+ cause: Type.Optional(CAUSE_SCHEMA),
16
+ },
17
+ { additionalProperties: false },
18
+ );
19
+ });
20
+ export type RegexWorkerReply<Result> =
21
+ | { readonly result: Result }
22
+ | { readonly error: WorkerError };
23
+
24
+ export function invalidWorkerResult(): HashlineError<"REGEX_WORKER_FAILED"> {
25
+ return new HashlineError("REGEX_WORKER_FAILED", "Regex worker returned an invalid result.");
26
+ }
27
+
28
+ export function workerReplyDecoder<T extends TSchema>(result: T) {
29
+ const schema = Type.Union([
30
+ Type.Object({ result }, { additionalProperties: false }),
31
+ Type.Object({ error: Type.Union(ERROR_SCHEMAS) }, { additionalProperties: false }),
32
+ ]);
33
+ return (value: unknown): RegexWorkerReply<Static<T>> | undefined => {
34
+ if (typeof value !== "object" || value === null) return undefined;
35
+ try {
36
+ const error: unknown = Reflect.get(value, "error");
37
+ // Structured cloning permits cycles and BigInt; reports must remain JSON-serializable.
38
+ if (typeof error === "object" && error !== null) JSON.stringify(error);
39
+ // The dynamic error union is validated against the same code-specific schemas.
40
+ return Value.Check(schema, value) ? (value as RegexWorkerReply<Static<T>>) : undefined;
41
+ } catch (error) {
42
+ if (error instanceof TypeError || error instanceof RangeError) return undefined;
43
+ throw error;
44
+ }
45
+ };
46
+ }
47
+
48
+ /** Restore an error workerReplyDecoder checked as the same HashlineError the worker threw. */
49
+ export function restoreWorkerError(error: WorkerError): HashlineError {
50
+ // The parameter ties facts to code; TypeScript cannot carry that link into the generic constructor.
51
+ const options = [
52
+ { facts: error.facts, cause: restoreCause(error.cause) },
53
+ ] as HashlineErrorArguments<ErrorCode>;
54
+ return new HashlineError(error.code, error.message, ...options);
55
+ }
@@ -0,0 +1,95 @@
1
+ /** Own one regex worker's timeout, cancellation, and cleanup; callers await each request. */
2
+ import { Worker, type ResourceLimits } from "node:worker_threads";
3
+ import { HashlineError } from "../core/errors.ts";
4
+ import { cancellationError, throwIfCancelled } from "./error-text.ts";
5
+ import {
6
+ restoreWorkerError,
7
+ invalidWorkerResult,
8
+ type RegexWorkerReply,
9
+ } from "./regex-worker-contract.ts";
10
+
11
+ export async function withRegexWorker<Input, Result, Output>(
12
+ entry: URL,
13
+ decode: (value: unknown) => RegexWorkerReply<Result> | undefined,
14
+ timeoutMs: number,
15
+ signal: AbortSignal | undefined,
16
+ execute: (run: (input: Input) => Promise<Result>) => Promise<Output>,
17
+ resourceLimits?: ResourceLimits,
18
+ ): Promise<Output> {
19
+ throwIfCancelled(signal);
20
+ const worker = new Worker(entry, { resourceLimits });
21
+ let failure: Error | undefined;
22
+ let pending: { resolve: (result: Result) => void; reject: (error: Error) => void } | undefined;
23
+ let timer: ReturnType<typeof setTimeout> | undefined;
24
+ const clear = () => {
25
+ clearTimeout(timer);
26
+ const previous = pending;
27
+ pending = undefined;
28
+ return previous;
29
+ };
30
+ const fail = (error: Error) => {
31
+ failure ??= error;
32
+ clear()?.reject(error);
33
+ };
34
+ const abort = () => fail(cancellationError());
35
+ worker.on("message", (value: unknown) => {
36
+ try {
37
+ const reply = decode(value);
38
+ if (!reply) fail(invalidWorkerResult());
39
+ else if ("error" in reply) fail(restoreWorkerError(reply.error));
40
+ else clear()?.resolve(reply.result);
41
+ } catch (error) {
42
+ fail(
43
+ new HashlineError("REGEX_WORKER_FAILED", "Could not decode the regex worker result.", {
44
+ cause: error,
45
+ }),
46
+ );
47
+ }
48
+ });
49
+ worker.on("error", (error) =>
50
+ fail(new HashlineError("REGEX_WORKER_FAILED", "Regex worker failed.", { cause: error })),
51
+ );
52
+ worker.on("exit", (exitCode) =>
53
+ fail(
54
+ new HashlineError("REGEX_WORKER_FAILED", "Regex worker exited before replying.", {
55
+ facts: { exitCode },
56
+ }),
57
+ ),
58
+ );
59
+ signal?.addEventListener("abort", abort, { once: true });
60
+ // Keep dispatch asynchronous so cancellation can be observed before posting a request.
61
+ const run = (input: Input): Promise<Result> =>
62
+ Promise.resolve().then(() => {
63
+ throwIfCancelled(signal);
64
+ if (failure) throw failure;
65
+ return new Promise<Result>((resolve, reject) => {
66
+ pending = { resolve, reject };
67
+ timer = setTimeout(
68
+ () =>
69
+ fail(
70
+ new HashlineError("REGEX_TIMEOUT", "Regex evaluation timed out.", {
71
+ facts: { timeoutMs },
72
+ }),
73
+ ),
74
+ timeoutMs,
75
+ );
76
+ try {
77
+ worker.postMessage(input);
78
+ } catch (error) {
79
+ fail(
80
+ new HashlineError("REGEX_WORKER_FAILED", "Could not send the regex request.", {
81
+ cause: error,
82
+ }),
83
+ );
84
+ }
85
+ });
86
+ });
87
+ try {
88
+ if (signal?.aborted) abort();
89
+ return await execute(run);
90
+ } finally {
91
+ clear();
92
+ signal?.removeEventListener("abort", abort);
93
+ await worker.terminate();
94
+ }
95
+ }