@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
@@ -24,14 +24,14 @@ import {
24
24
  contains,
25
25
  nativeCharacterRanges,
26
26
  foldRanges,
27
- membership,
28
27
  type Ranges,
28
+ acceptedClassStrings,
29
29
  classStrings,
30
30
  type CharacterNode,
31
31
  surrogatePair,
32
32
  } from "../core/character-set.ts";
33
33
  import { caseVariants } from "../core/case-fold.ts";
34
- import { parseQueryPattern } from "../core/search-analysis.ts";
34
+ import { analyzeQueryPattern } from "../core/search-analysis.ts";
35
35
  import type { GrepQuery } from "../core/search.ts";
36
36
 
37
37
  const LF = 0x0a;
@@ -219,7 +219,7 @@ function assertionPlans(elements: readonly AST.Element[], ctx: Context): readonl
219
219
  if (node.negate) {
220
220
  if (adjacent.length !== asserted.length) return [plan];
221
221
  return adjacent.map((item, at) =>
222
- restrict(plan, item, complement(asserted[at], everything(ctx)[0][1]), ctx),
222
+ restrict(plan, item, complement(asserted[at], maxElement(ctx)), ctx),
223
223
  );
224
224
  }
225
225
  let constrained = plan;
@@ -243,7 +243,7 @@ function assertionPlans(elements: readonly AST.Element[], ctx: Context): readonl
243
243
  plan = restrict(
244
244
  plan,
245
245
  other,
246
- isWord === node.negate ? word : complement(word, everything(ctx)[0][1]),
246
+ isWord === node.negate ? word : complement(word, maxElement(ctx)),
247
247
  ctx,
248
248
  );
249
249
  }
@@ -269,8 +269,8 @@ function assertionPlans(elements: readonly AST.Element[], ctx: Context): readonl
269
269
 
270
270
  const intersects = (ranges: Ranges, other: Ranges) => intersect(ranges, other).length !== 0;
271
271
 
272
- /** Everything one element can consume: one code point with u, one UTF-16 unit without. */
273
- const everything = (ctx: Context): Ranges => (ctx.unicode ? [[0, MAX_SCALAR]] : [[0, MAX_UNIT]]);
272
+ /** The largest value one element can consume: a code point with u, a UTF-16 unit without. */
273
+ const maxElement = (ctx: Context): number => (ctx.unicode ? MAX_SCALAR : MAX_UNIT);
274
274
 
275
275
  const folded = (ranges: Ranges, ctx: Context): Ranges =>
276
276
  ctx.ignoreCase ? foldRanges(ranges, ctx.unicode) : ranges;
@@ -378,11 +378,9 @@ function stringPattern(strings: readonly string[], ctx: Context): string {
378
378
  }
379
379
 
380
380
  function characterPattern(node: CharacterNode, ctx: Context): string {
381
- const strings = classStrings(node);
382
- if (!strings) return ANY_TEXT;
381
+ const accepted = acceptedClassStrings(node, nativeFlags(node, ctx));
382
+ if (!accepted) return ANY_TEXT;
383
383
  const ranges = scalarRanges(node, ctx);
384
- const accepts = membership(node.raw, nativeFlags(node, ctx));
385
- const accepted = strings.filter((value) => accepts.test(value));
386
384
  return choice([
387
385
  ...(ranges.length ? [unit(ranges, ctx)] : []),
388
386
  ...(accepted.length
@@ -457,9 +455,9 @@ function ignoreCaseAt(node: AST.Node, ctx: Context): boolean {
457
455
  }
458
456
 
459
457
  /**
460
- * Whether a group has always matched when its backreference is reached: the group precedes
461
- * the reference in one alternative, and nothing between the group and that alternative can
462
- * skip it (another alternative, a quantifier that allows zero, or a lookaround).
458
+ * Whether a group has always matched when its backreference is reached: the group executes
459
+ * before the reference in one alternative, and nothing between the group and that alternative
460
+ * can skip it (another alternative, a quantifier that allows zero, or a lookaround).
463
461
  */
464
462
  function participates(group: AST.CapturingGroup, reference: AST.Backreference): boolean {
465
463
  const ancestors = new Set<AST.Node>();
@@ -482,7 +480,16 @@ function participates(group: AST.CapturingGroup, reference: AST.Backreference):
482
480
  groupChild = node;
483
481
  }
484
482
  const elements: readonly AST.Node[] = common.elements;
485
- return elements.indexOf(groupChild) < elements.indexOf(referenceChild);
483
+ let backward = false;
484
+ // The nearest lookaround decides direction; a nested lookahead runs forward again.
485
+ for (let node: AST.Node | null = common.parent; node; node = node.parent) {
486
+ if (node.type !== "Assertion") continue;
487
+ backward = node.kind === "lookbehind";
488
+ break;
489
+ }
490
+ const groupPosition = elements.indexOf(groupChild);
491
+ const referencePosition = elements.indexOf(referenceChild);
492
+ return backward ? groupPosition > referencePosition : groupPosition < referencePosition;
486
493
  }
487
494
 
488
495
  /**
@@ -623,11 +630,9 @@ function finiteWords(node: AST.Element, ctx: Context): readonly string[] | undef
623
630
  const result: string[] = [];
624
631
  for (const [low, high] of ranges)
625
632
  for (let point = low; point <= high; point++) result.push(String.fromCodePoint(point));
626
- const strings = classStrings(node);
633
+ const strings = acceptedClassStrings(node, nativeFlags(node, ctx));
627
634
  if (!strings) return undefined;
628
- const accepts = membership(node.raw, nativeFlags(node, ctx));
629
635
  for (const value of strings) {
630
- if (!accepts.test(value)) continue;
631
636
  let words: readonly string[] = [""];
632
637
  for (const char of value) {
633
638
  const variants = ignoreCaseAt(node, ctx) ? caseVariants(char, ctx.unicode) : [char];
@@ -690,13 +695,14 @@ export function lineCandidatePatterns(query: GrepQuery): string[] | undefined {
690
695
  };
691
696
  const patterns: string[] = [];
692
697
  for (const pattern of query.patterns) {
693
- const parsed = parseQueryPattern(pattern, query.literal, query.flags);
694
- if (!parsed) return undefined;
695
- const translated = choice(
696
- bindingContexts(parsed, ctx).map((context) =>
697
- alternatives(parsed.alternatives, context, { first: true, last: true }),
698
+ const translated = analyzeQueryPattern(pattern, query.literal, query.flags, (parsed) =>
699
+ choice(
700
+ bindingContexts(parsed, ctx).map((context) =>
701
+ alternatives(parsed.alternatives, context, { first: true, last: true }),
702
+ ),
698
703
  ),
699
704
  );
705
+ if (translated === undefined) return undefined;
700
706
  if (
701
707
  translated.length + patterns.reduce((sum, value) => sum + value.length, 0) >
702
708
  MAX_LINE_PATTERN_UNITS
@@ -1,9 +1,8 @@
1
1
  import { test } from "node:test";
2
2
  import assert from "node:assert/strict";
3
- import { createHash } from "node:crypto";
4
3
  import { mkdtemp, rm, writeFile } from "node:fs/promises";
5
4
  import { tmpdir } from "node:os";
6
- import { byteRevision } from "./file-commit.ts";
5
+ import { byteRevision } from "./file-revision.ts";
7
6
  import { join } from "node:path";
8
7
  import { scanTextFile, scanTextLines } from "./text-stream.ts";
9
8
  import { splitLines } from "../core/lines.ts";
@@ -48,29 +47,40 @@ test("streamed lines preserve BOM, standalone CR, and boundaries split across ch
48
47
  assert.deepEqual(lines, splitLines(text));
49
48
  assert.equal(stats.totalLines, lines.length);
50
49
  assert.equal(stats.finalNewline, text === "" || text.endsWith("\n"));
51
- assert.equal(stats.hasCrLf, text.includes("\r\n"));
52
50
  assert.equal(stats.byteLength, Buffer.byteLength(text));
53
51
  }
54
52
  }));
55
53
 
56
- test("streamed byte digests preserve the source revision across BOM, CRLF, and chunk boundaries", async () =>
54
+ test("streamed scans → return the revision of every original byte and byte-based chunk progress", async () =>
57
55
  withFile(async (path) => {
58
- const source = Buffer.from(`\uFEFFfirst\r\n${"a".repeat(65536)}\r\nlast\r`);
59
- await writeFile(path, source);
60
- const first = createHash("sha256");
61
- const stats = await scanTextFile(path, { onBytes: (bytes) => first.update(bytes) });
62
- assert.equal(stats.hasCrLf, true);
63
- assert.equal(first.digest("hex"), byteRevision(source));
64
- const second = createHash("sha256");
65
- await scanTextLines(
66
- path,
67
- (number) => number === 1,
68
- () => {},
69
- {
70
- onBytes: (bytes) => second.update(bytes),
71
- },
72
- );
73
- assert.equal(second.digest("hex"), byteRevision(source));
56
+ const chunkBytes = 64 * 1024;
57
+ for (const source of [
58
+ Buffer.alloc(0),
59
+ Buffer.from("\uFEFF"),
60
+ Buffer.from("first\r\nlast\r\n"),
61
+ Buffer.from("\uFEFF" + "a".repeat(chunkBytes - 4) + "😀\r\nlast"),
62
+ ]) {
63
+ await writeFile(path, source);
64
+ const chunks: string[] = [];
65
+ const progress: number[] = [];
66
+ const stats = await scanTextFile(path, {
67
+ onChunk(text, bytesRead) {
68
+ chunks.push(text);
69
+ progress.push(bytesRead);
70
+ },
71
+ });
72
+ assert.equal(chunks.join(""), source.toString("utf8"));
73
+ assert.equal(stats.revision, byteRevision(source));
74
+ assert.equal(stats.byteLength, source.length);
75
+ assert.equal(progress.at(-1) ?? 0, source.length);
76
+ if (source.length > chunkBytes) assert.equal(progress[0], chunkBytes);
77
+ const selected = await scanTextLines(
78
+ path,
79
+ (number) => number === 1,
80
+ () => {},
81
+ );
82
+ assert.equal(selected.revision, stats.revision);
83
+ }
74
84
  }));
75
85
 
76
86
  test("streamed selection discards oversized content and still counts and reads subsequent lines", async () =>
@@ -132,7 +142,6 @@ test("lossy decoding reports invalid UTF-8 across chunk boundaries and preserves
132
142
  Buffer.from("\r\nlast"),
133
143
  ]);
134
144
  await writeFile(path, source);
135
- const hash = createHash("sha256");
136
145
  const lines: string[] = [];
137
146
  const stats = await scanTextLines(
138
147
  path,
@@ -140,21 +149,19 @@ test("lossy decoding reports invalid UTF-8 across chunk boundaries and preserves
140
149
  (line) => lines.push(line.text ?? ""),
141
150
  {
142
151
  decoding: "lossy",
143
- onBytes: (bytes) => hash.update(bytes),
144
152
  },
145
153
  );
146
154
  assert.equal(stats.validUtf8, false);
147
155
  assert.equal(stats.hasNul, false);
148
- assert.equal(stats.hasCrLf, true);
149
156
  assert.deepEqual(lines, splitLines(source.toString("utf8")));
150
- assert.equal(hash.digest("hex"), byteRevision(source));
157
+ assert.equal(stats.revision, byteRevision(source));
151
158
  await assert.rejects(
152
159
  scanTextFile(path),
153
160
  (error: unknown) => error instanceof Utf8DecodingError,
154
161
  );
155
162
  }));
156
163
 
157
- test("strict scans read all bytes but stop emitting text after a decoding error", async () =>
164
+ test("strict scans encounter invalid UTF-8 → stop emitting text and reject decoding", async () =>
158
165
  withFile(async (path) => {
159
166
  const chunkBytes = 64 * 1024;
160
167
  const prefix = Buffer.alloc(chunkBytes, "a");
@@ -163,18 +170,15 @@ test("strict scans read all bytes but stop emitting text after a decoding error"
163
170
  const source = Buffer.concat([prefix, invalid, Buffer.from("later text\n")]);
164
171
  await writeFile(path, source);
165
172
  const emitted: string[] = [];
166
- const scanned: Buffer[] = [];
167
173
  await assert.rejects(
168
174
  scanTextFile(path, {
169
175
  onChunk: (text) => {
170
176
  emitted.push(text);
171
177
  },
172
- onBytes: (bytes) => scanned.push(bytes),
173
178
  }),
174
179
  (error: unknown) => error instanceof Utf8DecodingError,
175
180
  );
176
181
  assert.equal(emitted.join(""), prefix.toString("utf8"));
177
- assert.deepEqual(Buffer.concat(scanned), source);
178
182
  }));
179
183
 
180
184
  test("lossy scans flush a multibyte sequence split across chunks and incomplete at EOF", async () =>
@@ -204,15 +208,12 @@ test("lossy scans without a text consumer report validity and retain all raw byt
204
208
  Buffer.from([0xff, 0xf0, 0x9f]),
205
209
  ]);
206
210
  await writeFile(path, source);
207
- const scanned: Buffer[] = [];
208
211
  const stats = await scanTextFile(path, {
209
- onBytes: (bytes) => scanned.push(bytes),
210
212
  decoding: "lossy",
211
213
  });
212
- assert.deepEqual(Buffer.concat(scanned), source);
214
+ assert.equal(stats.revision, byteRevision(source));
213
215
  assert.equal(stats.validUtf8, false);
214
216
  assert.equal(stats.hasNul, false);
215
- assert.equal(stats.hasCrLf, true);
216
217
  assert.equal(stats.totalLines, 2);
217
218
  assert.equal(stats.finalNewline, false);
218
219
  assert.equal(stats.byteLength, source.length);
@@ -230,17 +231,15 @@ test("NUL suppresses its chunk and all later text without flushing a pending seq
230
231
  await writeFile(path, source);
231
232
  for (const decoding of ["strict", "lossy"] as const) {
232
233
  const emitted: string[] = [];
233
- const scanned: Buffer[] = [];
234
234
  const stats = await scanTextFile(path, {
235
235
  onChunk: (text) => {
236
236
  emitted.push(text);
237
237
  },
238
- onBytes: (bytes) => scanned.push(bytes),
239
238
  decoding,
240
239
  });
241
240
  assert.equal(stats.hasNul, true);
242
241
  assert.equal(emitted.join(""), prefix.toString("utf8"));
243
- assert.deepEqual(Buffer.concat(scanned), source);
242
+ assert.equal(stats.revision, byteRevision(source));
244
243
  }
245
244
  }));
246
245
 
@@ -281,7 +280,7 @@ test("valid file truncated across a pending UTF-8 sequence → scans report a ch
281
280
  let changed = false;
282
281
  await assert.rejects(
283
282
  scanTextFile(path, {
284
- onBytes: () => {
283
+ onChunk: () => {
285
284
  if (changed) return;
286
285
  changed = true;
287
286
  truncateSync(path, chunkBytes - 1);
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Streaming text scans: one read of a file yields its bytes, its NUL and UTF-8 validity, line
2
+ * Streaming text scans: one read of a file yields its revision, its NUL and UTF-8 validity, line
3
3
  * statistics, and the decoded text or selected lines.
4
4
  *
5
5
  * @module pi-hashline-edit/pi
@@ -8,29 +8,32 @@ import { createReadStream } from "node:fs";
8
8
  import { createUtf8Decoder, Utf8DecodingError, type Utf8Decoding } from "../core/text.ts";
9
9
  import { throwIfCancelled } from "./error-text.ts";
10
10
  import { withFileRead } from "./file-read.ts";
11
+ import { createRevisionHasher } from "./file-revision.ts";
11
12
 
12
13
  const TEXT_READ_CHUNK_BYTES = 64 * 1024;
13
14
 
14
- /** Scan whole-file bytes; lossy decoding reports validity without rejecting malformed UTF-8. */
15
+ /**
16
+ * Scan whole-file bytes; lossy decoding reports validity without rejecting malformed UTF-8.
17
+ * The revision covers exactly the bytes this scan read; onChunk also receives the bytes read so far.
18
+ */
15
19
  export async function scanTextFile(
16
20
  path: string,
17
21
  options: {
18
- readonly onChunk?: (text: string) => void | Promise<void>;
22
+ readonly onChunk?: (text: string, bytesRead: number) => void | Promise<void>;
19
23
  readonly signal?: AbortSignal;
20
- readonly onBytes?: (bytes: Buffer) => void;
21
24
  readonly decoding?: Utf8Decoding;
22
25
  } = {},
23
26
  ) {
24
- const { onChunk, signal, onBytes, decoding = "strict" } = options;
27
+ const { onChunk, signal, decoding = "strict" } = options;
25
28
  return withFileRead(path, signal, async (handle) => {
26
29
  const decode = createUtf8Decoder();
27
30
  // Strict decoding always decides validity; lossy text is decoded only for a chunk consumer.
28
31
  const lossy = decoding === "lossy" && onChunk ? createUtf8Decoder("lossy") : undefined;
32
+ const revision = createRevisionHasher();
29
33
  let byteLength = 0;
30
34
  let lineFeeds = 0;
31
35
  let lastByte = -1;
32
36
  let hasNul = false;
33
- let hasCrLf = false;
34
37
  let decodingError: unknown;
35
38
  const stream = createReadStream(path, {
36
39
  fd: handle,
@@ -41,10 +44,9 @@ export async function scanTextFile(
41
44
  try {
42
45
  for await (const chunk of stream) {
43
46
  const bytes = chunk as Buffer;
44
- onBytes?.(bytes);
47
+ revision.update(bytes);
45
48
  byteLength += bytes.length;
46
49
  hasNul ||= bytes.includes(0);
47
- hasCrLf ||= (lastByte === 13 && bytes[0] === 10) || bytes.includes("\r\n");
48
50
  lastByte = bytes[bytes.length - 1];
49
51
  let offset = 0;
50
52
  while ((offset = bytes.indexOf(10, offset)) !== -1) {
@@ -63,7 +65,7 @@ export async function scanTextFile(
63
65
  }
64
66
  }
65
67
  if (lossy) text = lossy(bytes, true);
66
- if (text !== undefined) await onChunk?.(text);
68
+ if (text !== undefined) await onChunk?.(text, byteLength);
67
69
  }
68
70
  } catch (error) {
69
71
  // Node's stream abort raises its own AbortError; report the shared cancellation text.
@@ -83,14 +85,14 @@ export async function scanTextFile(
83
85
  }
84
86
  if (lossy) tail = lossy();
85
87
  else if (decodingError && decoding === "strict") throw decodingError;
86
- if (tail) await onChunk?.(tail);
88
+ if (tail) await onChunk?.(tail, byteLength);
87
89
  }
88
90
  return {
91
+ revision: revision.digest(),
89
92
  byteLength,
90
93
  totalLines: lineFeeds + (lastByte !== -1 && lastByte !== 10 ? 1 : 0),
91
94
  finalNewline: lastByte === -1 || lastByte === 10,
92
95
  hasNul,
93
- hasCrLf,
94
96
  validUtf8: !decodingError,
95
97
  };
96
98
  });
@@ -112,7 +114,6 @@ export async function scanTextLines(
112
114
  options: {
113
115
  readonly signal?: AbortSignal;
114
116
  readonly maxLineBytes?: number;
115
- readonly onBytes?: (bytes: Buffer) => void;
116
117
  readonly decoding?: Utf8Decoding;
117
118
  } = {},
118
119
  ) {
@@ -143,10 +144,9 @@ export async function scanTextLines(
143
144
  number++;
144
145
  selected = select(number);
145
146
  };
146
- const { signal, onBytes, decoding } = options;
147
+ const { signal, decoding } = options;
147
148
  const stats = await scanTextFile(path, {
148
149
  signal,
149
- onBytes,
150
150
  decoding,
151
151
  onChunk: (text) => {
152
152
  let start = 0;
@@ -7,16 +7,20 @@
7
7
  * unusual arguments go through the same funnel instead of calling `execute`.
8
8
  */
9
9
 
10
- import { validateToolArguments } from "@earendil-works/pi-ai";
10
+ import { validateToolArguments, type Tool, type ToolCall } from "@earendil-works/pi-ai";
11
11
  import type { TestContext } from "node:test";
12
12
  import type { ExtensionToolContext } from "@earendil-works/pi-coding-agent";
13
13
  import { openTestSession } from "../testing/session.testing.ts";
14
14
 
15
- interface CallableTool {
16
- readonly name: string;
17
- readonly parameters: unknown;
15
+ interface CallableTool extends Tool {
18
16
  prepareArguments?(args: unknown): unknown;
19
- execute(...args: any[]): Promise<any>;
17
+ execute(
18
+ toolCallId: string,
19
+ params: unknown,
20
+ signal: AbortSignal | undefined,
21
+ onUpdate: unknown,
22
+ ctx: unknown,
23
+ ): Promise<unknown>;
20
24
  }
21
25
 
22
26
  export interface ToolCallOptions {
@@ -27,14 +31,20 @@ export interface ToolCallOptions {
27
31
  }
28
32
 
29
33
  /** prepareArguments → schema validation → execute, failing the way Pi reports invalid calls. */
34
+ export function callTool<T extends CallableTool>(
35
+ tool: T,
36
+ args: unknown,
37
+ options?: ToolCallOptions,
38
+ ): ReturnType<T["execute"]>;
30
39
  export async function callTool(tool: CallableTool, args: unknown, options: ToolCallOptions = {}) {
31
40
  const toolCallId = options.toolCallId ?? "test";
32
41
  const prepared = tool.prepareArguments ? tool.prepareArguments(args) : args;
33
- const validated = validateToolArguments(tool as never, {
42
+ const validated: unknown = validateToolArguments(tool, {
34
43
  type: "toolCall",
35
44
  id: toolCallId,
36
45
  name: tool.name,
37
- arguments: prepared as never,
46
+ // Pi owns shape checking and coercion at this external boundary.
47
+ arguments: prepared as ToolCall["arguments"],
38
48
  });
39
49
  return tool.execute(toolCallId, validated, options.signal, options.onUpdate, options.ctx);
40
50
  }
@@ -13,13 +13,13 @@ import {
13
13
  withThenRunSchema,
14
14
  type ThenRunInput,
15
15
  } from "./action-fusion.ts";
16
- import { commitFile, type CommitResult } from "./file-commit.ts";
16
+ import { commitFile } from "./file-commit.ts";
17
17
  import { executeMutation, type ActionFusionExecutor } from "./mutation-runner.ts";
18
18
  import { throwIfCancelled } from "./error-text.ts";
19
19
  import { createArgumentPreparer } from "./argument-validation.ts";
20
20
  import { defaultOutputBudgets, type OutputBudgetProvider } from "./budgets.ts";
21
21
  import { unwritableTextError } from "../core/text.ts";
22
- import { reportLines, renderToolError } from "./render.ts";
22
+ import { reportLines, renderToolError, splitReport } from "./render.ts";
23
23
  import type { MutationResultDetails } from "./mutation-result.ts";
24
24
  import type { ReportDetails } from "./report.ts";
25
25
 
@@ -37,11 +37,9 @@ const writeSchema = Type.Object(
37
37
  { additionalProperties: false },
38
38
  );
39
39
 
40
- function createWriteSchema(actionFusion: boolean) {
41
- return withThenRunSchema(writeSchema, "write", actionFusion);
42
- }
43
40
  type WriteParams = Static<typeof writeSchema> & { then_run?: ThenRunInput };
44
- type WriteMutationDetails = CommitResult & { path: string };
41
+ /** write shows the built-in card; its report states every fact. */
42
+ type WriteMutationDetails = object;
45
43
  type WriteDetails = MutationResultDetails<WriteMutationDetails>;
46
44
  /** The write card's call line shows the content; the command card owns then_run. */
47
45
  const WRITE_CARD_SHOWN = new Set(["publication", "created", "then_run", "progressError"]);
@@ -54,7 +52,7 @@ export function makeWriteOverride(
54
52
  fusion?: ActionFusionExecutor,
55
53
  budgets: OutputBudgetProvider = defaultOutputBudgets,
56
54
  ) {
57
- const parameters = createWriteSchema(fusion !== undefined);
55
+ const parameters = withThenRunSchema(writeSchema, "write", fusion !== undefined);
58
56
  const builtin = createWriteToolDefinition(cwd);
59
57
  return {
60
58
  name: "write" as const,
@@ -86,8 +84,8 @@ export function makeWriteOverride(
86
84
  theme: Theme,
87
85
  context: WriteRenderContext,
88
86
  ) {
89
- if (context.isError) return renderToolError(result, theme, options.expanded);
90
- const report = result.details?.report;
87
+ if (context.isError) return renderToolError(result, "write", theme, options.expanded);
88
+ const { report } = splitReport(result);
91
89
  const facts = report ? reportLines(report, theme, WRITE_CARD_SHOWN) : [];
92
90
  if (facts.length) return new Text(facts.join("\n"), 0, 0);
93
91
  return builtin.renderResult!({ ...result, details: undefined }, options, theme, context);
@@ -105,7 +103,7 @@ export function makeWriteOverride(
105
103
  cwd,
106
104
  fusion,
107
105
  budgets,
108
- async run(mutationParams, { absolutePath, displayPath, signal }) {
106
+ async run(mutationParams, { absolutePath, signal }) {
109
107
  throwIfCancelled(signal);
110
108
  const commit = await commitFile(absolutePath, mutationParams.content, {
111
109
  mode: mutationParams.mode,
@@ -113,7 +111,7 @@ export function makeWriteOverride(
113
111
  });
114
112
  return {
115
113
  commit,
116
- details: { path: displayPath, ...commit },
114
+ details: {},
117
115
  facts: commit.created ? { created: true } : {},
118
116
  };
119
117
  },