@criogaid/pi-hashline-edit 0.13.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) hide show
  1. package/README.md +18 -12
  2. package/README.zh-CN.md +18 -12
  3. package/package.json +8 -1
  4. package/src/core/AGENTS.md +3 -1
  5. package/src/core/apply.ts +110 -117
  6. package/src/core/character-set.ts +2 -3
  7. package/src/core/copy-span.ts +15 -0
  8. package/src/core/errors.ts +24 -9
  9. package/src/core/lines.ts +71 -17
  10. package/src/core/ranges.ts +5 -4
  11. package/src/core/replace-schema.ts +3 -1
  12. package/src/core/replace.ts +50 -29
  13. package/src/core/search-analysis.ts +21 -22
  14. package/src/core/search.ts +15 -32
  15. package/src/core/types.ts +3 -0
  16. package/src/index.ts +47 -39
  17. package/src/pi/AGENTS.md +30 -19
  18. package/src/pi/action-fusion.ts +284 -211
  19. package/src/pi/argument-diagnostics.ts +50 -37
  20. package/src/pi/argument-error.ts +2 -2
  21. package/src/pi/argument-validation.ts +163 -66
  22. package/src/pi/budgets.ts +12 -0
  23. package/src/pi/diagnostic-buffer.ts +12 -11
  24. package/src/pi/edit-tool.ts +138 -115
  25. package/src/pi/error-text.ts +10 -2
  26. package/src/pi/failure-context.ts +24 -37
  27. package/src/pi/file-commit.ts +131 -164
  28. package/src/pi/file-read.ts +122 -31
  29. package/src/pi/fusion-arguments.ts +214 -0
  30. package/src/pi/fusion-card.ts +102 -60
  31. package/src/pi/grep-candidates.ts +35 -22
  32. package/src/pi/grep-output.ts +197 -190
  33. package/src/pi/grep-render.ts +22 -13
  34. package/src/pi/grep-reread.ts +7 -6
  35. package/src/pi/grep-scope.ts +31 -16
  36. package/src/pi/grep-search.ts +56 -47
  37. package/src/pi/grep-tool.ts +35 -33
  38. package/src/pi/grep-worker.ts +3 -4
  39. package/src/pi/mutation-diff.ts +238 -0
  40. package/src/pi/mutation-result.ts +102 -79
  41. package/src/pi/mutation-runner.ts +107 -84
  42. package/src/pi/native-bash.ts +41 -0
  43. package/src/pi/path.ts +59 -6
  44. package/src/pi/read-tool.ts +173 -138
  45. package/src/pi/regex-worker.ts +14 -8
  46. package/src/pi/render.ts +101 -54
  47. package/src/pi/replace-regex.ts +1 -1
  48. package/src/pi/replace-tool.ts +14 -7
  49. package/src/pi/report-cause.ts +34 -17
  50. package/src/pi/report-schema.ts +184 -85
  51. package/src/pi/report.ts +133 -64
  52. package/src/pi/rg-process.ts +68 -48
  53. package/src/pi/schema.ts +4 -0
  54. package/src/pi/text-stream.ts +81 -87
  55. package/src/pi/workspace-cwd.js +2 -0
  56. package/src/pi/workspace.ts +46 -0
  57. package/src/pi/write-tool.ts +19 -13
  58. package/src/core/apply.test.ts +0 -644
  59. package/src/core/case-fold.test.ts +0 -35
  60. package/src/core/character-set.test.ts +0 -97
  61. package/src/core/errors.test.ts +0 -39
  62. package/src/core/hash.test.ts +0 -64
  63. package/src/core/lines.test.ts +0 -63
  64. package/src/core/ranges.test.ts +0 -123
  65. package/src/core/replace.test.ts +0 -187
  66. package/src/core/search-analysis.test.ts +0 -210
  67. package/src/core/search-matrix.test.ts +0 -64
  68. package/src/core/search-matrix.testing.ts +0 -171
  69. package/src/core/search.test.ts +0 -132
  70. package/src/core/text.test.ts +0 -52
  71. package/src/integration/config-registration.test.ts +0 -291
  72. package/src/integration/fusion-dispatch.test.ts +0 -320
  73. package/src/integration/grep-errors.test.ts +0 -81
  74. package/src/integration/grep-flags.test.ts +0 -76
  75. package/src/integration/grep-js-completeness.test.ts +0 -278
  76. package/src/integration/grep-line-candidates.test.ts +0 -201
  77. package/src/integration/grep-matrix.test.ts +0 -118
  78. package/src/integration/grep-order.test.ts +0 -78
  79. package/src/integration/grep-path-matrix.test.ts +0 -128
  80. package/src/integration/grep-prefilter-coverage.test.ts +0 -204
  81. package/src/integration/grep-process-limits.test.ts +0 -122
  82. package/src/integration/grep-regex.test.ts +0 -412
  83. package/src/integration/grep-rg.test.ts +0 -1659
  84. package/src/integration/grep-scan-budget.test.ts +0 -111
  85. package/src/integration/grep-translation.test.ts +0 -199
  86. package/src/integration/large-text.test.ts +0 -70
  87. package/src/integration/model-budget-lifecycle.test.ts +0 -186
  88. package/src/integration/mutation-file-types.test.ts +0 -30
  89. package/src/integration/mutation-file-types.testing.ts +0 -33
  90. package/src/integration/npm-package.test.ts +0 -19
  91. package/src/integration/npm-package.testing.ts +0 -243
  92. package/src/integration/publication-read-changes.test.ts +0 -454
  93. package/src/integration/read-changes.test.ts +0 -98
  94. package/src/integration/replace-package.test.ts +0 -22
  95. package/src/integration/replace-package.testing.ts +0 -36
  96. package/src/integration/replace-worker-boundary.test.ts +0 -127
  97. package/src/integration/report-replay.test.ts +0 -91
  98. package/src/integration/utf8-errors.test.ts +0 -46
  99. package/src/pi/action-fusion.test.ts +0 -659
  100. package/src/pi/action-fusion.testing.ts +0 -38
  101. package/src/pi/anchor-format.test.ts +0 -124
  102. package/src/pi/argument-error.testing.ts +0 -46
  103. package/src/pi/argument-format.test.ts +0 -196
  104. package/src/pi/argument-validation.test.ts +0 -1007
  105. package/src/pi/codemode.test.ts +0 -101
  106. package/src/pi/config.test.ts +0 -204
  107. package/src/pi/diagnostic-buffer.test.ts +0 -115
  108. package/src/pi/directory-sync.test.ts +0 -57
  109. package/src/pi/execute.test.ts +0 -1257
  110. package/src/pi/extension-loading.test.ts +0 -14
  111. package/src/pi/extension-loading.testing.ts +0 -3
  112. package/src/pi/failure-context.test.ts +0 -370
  113. package/src/pi/failure-path.test.ts +0 -289
  114. package/src/pi/file-commit.test.ts +0 -628
  115. package/src/pi/file-read.test.ts +0 -29
  116. package/src/pi/file-snapshot.test.ts +0 -22
  117. package/src/pi/fusion-card-interaction.test.ts +0 -143
  118. package/src/pi/fusion-card.test.ts +0 -353
  119. package/src/pi/grep-candidates.test.ts +0 -26
  120. package/src/pi/grep-matrix.test.ts +0 -68
  121. package/src/pi/grep-order.test.ts +0 -447
  122. package/src/pi/grep-output.testing.ts +0 -24
  123. package/src/pi/grep-rg.testing.ts +0 -73
  124. package/src/pi/grep.test.ts +0 -1670
  125. package/src/pi/model-budgets.test.ts +0 -96
  126. package/src/pi/mutation-outcome.testing.ts +0 -20
  127. package/src/pi/mutation-result.test.ts +0 -96
  128. package/src/pi/output-budgets.test.ts +0 -221
  129. package/src/pi/pi.test.ts +0 -158
  130. package/src/pi/read-delegation.test.ts +0 -119
  131. package/src/pi/read.test.ts +0 -735
  132. package/src/pi/regex-worker.test.ts +0 -42
  133. package/src/pi/registration.test.ts +0 -549
  134. package/src/pi/render.test.ts +0 -841
  135. package/src/pi/replace.test.ts +0 -634
  136. package/src/pi/report-failure.testing.ts +0 -27
  137. package/src/pi/report.test.ts +0 -533
  138. package/src/pi/result-safety.test.ts +0 -597
  139. package/src/pi/rg-process.test.ts +0 -133
  140. package/src/pi/rg-regex.test.ts +0 -40
  141. package/src/pi/text-stream.test.ts +0 -281
  142. package/src/pi/tool-call.testing.ts +0 -61
  143. package/src/pi/tool-factories.testing.ts +0 -59
  144. package/src/pi/write.test.ts +0 -256
  145. package/src/testing/extension-loader.testing.ts +0 -24
  146. package/src/testing/installation.testing.ts +0 -77
  147. package/src/testing/process.testing.ts +0 -33
  148. package/src/testing/regex-host.testing.ts +0 -20
  149. package/src/testing/regex-translation-corpus.ts +0 -267
  150. package/src/testing/rg-line-listing.fixture.mjs +0 -7
  151. package/src/testing/run-tests.ts +0 -47
  152. package/src/testing/session.testing.ts +0 -127
@@ -1,133 +0,0 @@
1
- import { test, type TestContext } from "node:test";
2
- import assert from "node:assert/strict";
3
- import childProcess from "node:child_process";
4
- import { syncBuiltinESMExports } from "node:module";
5
- import { Readable } from "node:stream";
6
- import { searchDiagnostic, runRgLines } from "./rg-process.ts";
7
- import { fileURLToPath } from "node:url";
8
- import { HashlineError } from "../core/errors.ts";
9
-
10
- test("grep search exit status → accepts no matches and preserves failure diagnostics", () => {
11
- for (const [code, stopped, stderr, expected] of [
12
- [0, false, "", undefined],
13
- [1, false, "", undefined],
14
- [2, false, " \n", "ripgrep exited with code 2."],
15
- [null, false, "", "ripgrep exited with code null."],
16
- [null, true, "", undefined],
17
- [2, false, " regex parse error\n", "regex parse error"],
18
- [null, true, " regex parse error\n", "regex parse error"],
19
- ] as const) {
20
- assert.deepEqual(
21
- searchDiagnostic({ code, stderr, stopped }),
22
- expected === undefined ? undefined : { reason: expected },
23
- JSON.stringify({ code, stderr, stopped }),
24
- );
25
- }
26
- });
27
-
28
- const listingFixture = fileURLToPath(
29
- new URL("../testing/rg-line-listing.fixture.mjs", import.meta.url),
30
- );
31
- const parserTimeoutMs = 5_000;
32
-
33
- async function parseListing(
34
- t: TestContext,
35
- chunks: readonly string[],
36
- maxLines = 10,
37
- stop = false,
38
- splitChunks?: readonly Buffer[],
39
- ) {
40
- const spawn = childProcess.spawn;
41
- const mock = t.mock.method(childProcess, "spawn", (...args: Parameters<typeof spawn>) => {
42
- const child = spawn(process.execPath, args[1] ?? [], args[2]);
43
- if (splitChunks) {
44
- assert.ok(child.stdout);
45
- const stream = Readable.from(splitChunks);
46
- t.mock.method(child.stdout, Symbol.asyncIterator, () => stream[Symbol.asyncIterator]());
47
- }
48
- return child;
49
- });
50
- syncBuiltinESMExports();
51
- try {
52
- const files: { path: string; lines: readonly number[] | undefined }[] = [];
53
- const result = await runRgLines(
54
- [
55
- listingFixture,
56
- JSON.stringify(chunks.map((chunk) => Buffer.from(chunk).toString("base64"))),
57
- ...(stop ? ["wait"] : []),
58
- ],
59
- AbortSignal.timeout(parserTimeoutMs),
60
- maxLines,
61
- (path, lines) => {
62
- files.push({ path, lines });
63
- return !stop;
64
- },
65
- );
66
- return { files, result };
67
- } finally {
68
- mock.mock.restore();
69
- syncBuiltinESMExports();
70
- }
71
- }
72
-
73
- test("line listing split at every byte → newline paths, empty rows, and grouped files survive", async (t) => {
74
- const listing = Buffer.from(
75
- "dir\n文件.txt\0" + "1:\n2:x\n10:[Omitted long matching line]\n\n" + "other.txt\0" + "3:y\n\n",
76
- );
77
- for (let split = 1; split < listing.length; split++) {
78
- const { files, result } = await parseListing(t, [], 10, false, [
79
- listing.subarray(0, split),
80
- listing.subarray(split),
81
- ]);
82
- assert.deepEqual(
83
- files,
84
- [
85
- { path: "dir\n文件.txt", lines: [1, 2, 10] },
86
- { path: "other.txt", lines: [3] },
87
- ],
88
- `split=${split}`,
89
- );
90
- assert.equal(result.code, 0);
91
- assert.equal(result.stopped, false);
92
- }
93
- });
94
-
95
- test("line listing exceeds maxLines → only the overflowing file requests all-line review", async (t) => {
96
- for (const maxLines of [2, 3]) {
97
- const { files } = await parseListing(
98
- t,
99
- ["many\0" + "1:x\n2:y\n3:z\n\nfew\0" + "1:\n\n"],
100
- maxLines,
101
- );
102
- assert.deepEqual(files, [
103
- { path: "many", lines: maxLines === 2 ? undefined : [1, 2, 3] },
104
- { path: "few", lines: [1] },
105
- ]);
106
- }
107
- });
108
-
109
- test("line consumer returns false → process stops before the next file", async (t) => {
110
- const { files, result } = await parseListing(
111
- t,
112
- ["first\0" + "1:x\n\nsecond\0" + "2:y\n\n"],
113
- 10,
114
- true,
115
- );
116
- assert.deepEqual(files, [{ path: "first", lines: [1] }]);
117
- assert.equal(result.stopped, true);
118
- });
119
-
120
- test("line listing ends with incomplete path or row → RIPGREP_FAILED", async (t) => {
121
- for (const record of ["unfinished-path", "file\0" + "1:x", "file\0" + "1"]) {
122
- await assert.rejects(
123
- parseListing(t, [record]),
124
- (error: unknown) => error instanceof HashlineError && error.errorCode === "RIPGREP_FAILED",
125
- );
126
- }
127
- });
128
-
129
- test("line listing ends after a complete row → flush the final file without a separator", async (t) => {
130
- const { files, result } = await parseListing(t, ["final\0" + "1:x\n"]);
131
- assert.deepEqual(files, [{ path: "final", lines: [1] }]);
132
- assert.equal(result.code, 0);
133
- });
@@ -1,40 +0,0 @@
1
- import assert from "node:assert/strict";
2
- import { test } from "node:test";
3
- import { lineCandidatePatterns } from "./rg-regex.ts";
4
-
5
- // These expressions are the byte-level boundary contract, including deliberate widening.
6
- for (const [pattern, expected] of [
7
- ["a$", "a(?:[\\r\\x{2028}\\x{2029}]|\\r?$)"],
8
- ["[A-Z]{10,}", "(?:[A-Z]){10,}"],
9
- ["(?m:^)b", "(?:^|[\\r\\x{2028}\\x{2029}])b"],
10
- ["(\\w)\\1{4}", "[0-9A-Z_a-z](?:[0-9A-Z_a-z]){4,4}"],
11
- ] as const) {
12
- test(`line candidates ${pattern} → preserve required byte positions`, () => {
13
- assert.deepEqual(
14
- lineCandidatePatterns({
15
- patterns: [pattern],
16
- literal: false,
17
- ignoreCase: false,
18
- multiline: false,
19
- }),
20
- [expected],
21
- );
22
- });
23
- }
24
-
25
- test("deeply nested pattern → line candidates retain the native match", () => {
26
- for (const depth of [50, 200, 500, 1_000, 2_000, 4_000]) {
27
- const pattern = `${"(?:".repeat(depth)}A${")".repeat(depth)}`;
28
- assert.equal(new RegExp(pattern).test("A"), true);
29
- const candidates = lineCandidatePatterns({
30
- patterns: [pattern],
31
- literal: false,
32
- ignoreCase: false,
33
- multiline: false,
34
- });
35
- // An unavailable line analysis delegates candidate discovery to the file prefilter.
36
- assert.ok(
37
- candidates === undefined || candidates.some((candidate) => new RegExp(candidate).test("A")),
38
- );
39
- }
40
- });
@@ -1,281 +0,0 @@
1
- import { test } from "node:test";
2
- import assert from "node:assert/strict";
3
- import { mkdtemp, rm, writeFile } from "node:fs/promises";
4
- import { tmpdir } from "node:os";
5
- import { byteRevision } from "./file-revision.ts";
6
- import { join } from "node:path";
7
- import { scanTextFile, scanTextLines } from "./text-stream.ts";
8
- import { splitLines } from "../core/lines.ts";
9
- import { isUtf8 } from "node:buffer";
10
- import { readFile } from "node:fs/promises";
11
- import { truncateSync } from "node:fs";
12
- import { Utf8DecodingError } from "../core/text.ts";
13
- import { HashlineError } from "../core/errors.ts";
14
-
15
- async function withFile(run: (path: string) => Promise<void>) {
16
- const directory = await mkdtemp(join(tmpdir(), "hashline-stream-"));
17
- try {
18
- await run(join(directory, "text"));
19
- } finally {
20
- await rm(directory, { recursive: true, force: true });
21
- }
22
- }
23
-
24
- test("streamed lines preserve BOM, standalone CR, and boundaries split across chunks", async () =>
25
- withFile(async (path) => {
26
- for (const text of [
27
- "",
28
- "\n",
29
- "\n\n",
30
- "a\r",
31
- "a\rb\n",
32
- "\uFEFFa\r\nb\nlast",
33
- "x".repeat(65535) + "😀\r\nnext\r",
34
- "x".repeat(65535) + "\r\nlast\n",
35
- ]) {
36
- await writeFile(path, text);
37
- const lines: string[] = [];
38
- const stats = await scanTextLines(
39
- path,
40
- () => true,
41
- (line) => {
42
- assert.equal(line.number, lines.length + 1);
43
- assert.equal(line.byteLength, Buffer.byteLength(line.text!));
44
- lines.push(line.text!);
45
- },
46
- {},
47
- );
48
- assert.deepEqual(lines, splitLines(text));
49
- assert.equal(stats.totalLines, lines.length);
50
- assert.equal(stats.finalNewline, text === "" || text.endsWith("\n"));
51
- }
52
- }));
53
-
54
- test("streamed scans → return the revision of every original byte and byte-based chunk progress", async () =>
55
- withFile(async (path) => {
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(progress.at(-1) ?? 0, source.length);
75
- if (source.length > chunkBytes) assert.equal(progress[0], chunkBytes);
76
- const selected = await scanTextLines(
77
- path,
78
- (number) => number === 1,
79
- () => {},
80
- {},
81
- );
82
- assert.equal(selected.revision, stats.revision);
83
- }
84
- }));
85
-
86
- test("streamed selection discards oversized content and still counts and reads subsequent lines", async () =>
87
- withFile(async (path) => {
88
- await writeFile(path, "z".repeat(2 * 1024 * 1024) + "\n界\r\nkeep\nignored\n");
89
- const seen: unknown[] = [];
90
- const stats = await scanTextLines(
91
- path,
92
- (number) => number <= 3,
93
- (line) => seen.push(line),
94
- { maxLineBytes: 4 },
95
- );
96
- assert.equal(stats.totalLines, 4);
97
- assert.deepEqual(seen, [
98
- { number: 1, byteLength: 2 * 1024 * 1024, carriageReturns: 0, text: undefined },
99
- { number: 2, byteLength: 3, carriageReturns: 0, text: "界" },
100
- { number: 3, byteLength: 4, carriageReturns: 0, text: "keep" },
101
- ]);
102
- }));
103
-
104
- test("streamed validation checks the entire file and gives NUL precedence over malformed UTF-8", async () =>
105
- withFile(async (path) => {
106
- await writeFile(
107
- path,
108
- Buffer.concat([Buffer.from("visible\n"), Buffer.alloc(65536, 97), Buffer.from([0xf0, 0x9f])]),
109
- );
110
- await assert.rejects(
111
- scanTextLines(
112
- path,
113
- (number) => number === 1,
114
- () => {},
115
- {},
116
- ),
117
- (error: unknown) => error instanceof Utf8DecodingError,
118
- );
119
- await writeFile(
120
- path,
121
- Buffer.concat([Buffer.from([0xff]), Buffer.alloc(65536, 97), Buffer.from([0])]),
122
- );
123
- assert.equal((await scanTextFile(path)).hasNul, true);
124
- }));
125
-
126
- test("streamed reads propagate cancellation", async () =>
127
- withFile(async (path) => {
128
- await writeFile(path, "a".repeat(2 * 65536));
129
- const controller = new AbortController();
130
- await assert.rejects(
131
- scanTextFile(path, { onChunk: () => controller.abort(), signal: controller.signal }),
132
- (error: unknown) => error instanceof HashlineError && error.errorCode === "OPERATION_ABORTED",
133
- );
134
- }));
135
-
136
- test("lossy decoding reports invalid UTF-8 across chunk boundaries and preserves raw revisions", async () =>
137
- withFile(async (path) => {
138
- const source = Buffer.concat([
139
- Buffer.from("\uFEFF" + "a".repeat(65532)),
140
- Buffer.from([0xf0, 0x9f]),
141
- Buffer.from("\r\nneedle "),
142
- Buffer.from([0xff]),
143
- Buffer.from("\r\nlast"),
144
- ]);
145
- await writeFile(path, source);
146
- const lines: string[] = [];
147
- const stats = await scanTextLines(
148
- path,
149
- () => true,
150
- (line) => lines.push(line.text ?? ""),
151
- {
152
- decoding: "lossy",
153
- },
154
- );
155
- assert.equal(stats.validUtf8, false);
156
- assert.equal(stats.hasNul, false);
157
- assert.deepEqual(lines, splitLines(source.toString("utf8")));
158
- assert.equal(stats.revision, byteRevision(source));
159
- await assert.rejects(
160
- scanTextFile(path),
161
- (error: unknown) => error instanceof Utf8DecodingError,
162
- );
163
- }));
164
-
165
- test("strict scans encounter invalid UTF-8 → stop emitting text and reject decoding", async () =>
166
- withFile(async (path) => {
167
- const chunkBytes = 64 * 1024;
168
- const prefix = Buffer.alloc(chunkBytes, "a");
169
- const invalid = Buffer.alloc(chunkBytes, "b");
170
- invalid[0] = 0xff;
171
- const source = Buffer.concat([prefix, invalid, Buffer.from("later text\n")]);
172
- await writeFile(path, source);
173
- const emitted: string[] = [];
174
- await assert.rejects(
175
- scanTextFile(path, {
176
- onChunk: (text) => {
177
- emitted.push(text);
178
- },
179
- }),
180
- (error: unknown) => error instanceof Utf8DecodingError,
181
- );
182
- assert.equal(emitted.join(""), prefix.toString("utf8"));
183
- }));
184
-
185
- test("lossy scans flush a multibyte sequence split across chunks and incomplete at EOF", async () =>
186
- withFile(async (path) => {
187
- const chunkBytes = 64 * 1024;
188
- const prefix = Buffer.alloc(chunkBytes - 1, "a");
189
- const source = Buffer.concat([prefix, Buffer.from([0xf0, 0x9f])]);
190
- await writeFile(path, source);
191
- const emitted: string[] = [];
192
- const stats = await scanTextFile(path, {
193
- onChunk: (text) => {
194
- emitted.push(text);
195
- },
196
- decoding: "lossy",
197
- });
198
- assert.equal(emitted.join(""), prefix.toString("utf8") + "�");
199
- assert.equal(emitted.at(-1), "�");
200
- assert.equal(stats.validUtf8, false);
201
- assert.equal(stats.hasNul, false);
202
- }));
203
-
204
- test("NUL suppresses its chunk and all later text without flushing a pending sequence", async () =>
205
- withFile(async (path) => {
206
- const chunkBytes = 64 * 1024;
207
- const prefix = Buffer.alloc(chunkBytes - 1, "a");
208
- const source = Buffer.concat([
209
- prefix,
210
- Buffer.from([0xf0, 0, 0x9f]),
211
- Buffer.alloc(chunkBytes, "b"),
212
- ]);
213
- await writeFile(path, source);
214
- for (const decoding of ["strict", "lossy"] as const) {
215
- const emitted: string[] = [];
216
- const stats = await scanTextFile(path, {
217
- onChunk: (text) => {
218
- emitted.push(text);
219
- },
220
- decoding,
221
- });
222
- assert.equal(stats.hasNul, true);
223
- assert.equal(emitted.join(""), prefix.toString("utf8"));
224
- assert.equal(stats.revision, byteRevision(source));
225
- }
226
- }));
227
-
228
- test("NUL takes precedence over earlier malformed UTF-8 in strict and lossy scans", async () =>
229
- withFile(async (path) => {
230
- const chunkBytes = 64 * 1024;
231
- const invalid = Buffer.alloc(chunkBytes, "a");
232
- invalid[0] = 0xff;
233
- const source = Buffer.concat([invalid, Buffer.from("\0later\n")]);
234
- await writeFile(path, source);
235
- for (const decoding of ["strict", "lossy"] as const) {
236
- const emitted: string[] = [];
237
- const stats = await scanTextFile(path, {
238
- onChunk: (text) => {
239
- emitted.push(text);
240
- },
241
- decoding,
242
- });
243
- assert.equal(stats.hasNul, true);
244
- assert.equal(stats.validUtf8, false);
245
- assert.equal(emitted.join(""), decoding === "strict" ? "" : invalid.toString("utf8"));
246
- }
247
- }));
248
-
249
- test("valid file truncated across a pending UTF-8 sequence → scans report a changed file", async () =>
250
- withFile(async (path) => {
251
- const chunkBytes = 64 * 1024;
252
- const source = Buffer.from(
253
- "x".repeat(chunkBytes - 1) +
254
- "中" +
255
- "x".repeat(chunkBytes - 3) +
256
- "中" +
257
- "tail".repeat(chunkBytes),
258
- );
259
- assert.equal(isUtf8(source), true);
260
- for (const decoding of ["strict", "lossy"] as const) {
261
- await writeFile(path, source);
262
- let changed = false;
263
- await assert.rejects(
264
- scanTextFile(path, {
265
- onChunk: () => {
266
- if (changed) return;
267
- changed = true;
268
- truncateSync(path, chunkBytes - 1);
269
- },
270
- decoding,
271
- }),
272
- (error: unknown) => {
273
- assert.ok(error instanceof Error);
274
- assert.match(error.message, /File changed/);
275
- assert.ok(!(error instanceof Utf8DecodingError));
276
- return true;
277
- },
278
- );
279
- assert.equal(isUtf8(await readFile(path)), true);
280
- }
281
- }));
@@ -1,61 +0,0 @@
1
- /**
2
- * Test support: invoke a tool the way Pi does.
3
- *
4
- * In production, input reaches `execute` only after Pi runs the tool's
5
- * `prepareArguments` and validates (and coerces) the result against the tool
6
- * schema. `execute` trusts that input, so tests that probe invalid or
7
- * unusual arguments go through the same funnel instead of calling `execute`.
8
- */
9
-
10
- import { validateToolArguments, type Tool, type ToolCall } from "@earendil-works/pi-ai";
11
- import type { TestContext } from "node:test";
12
- import type { ExtensionToolContext } from "@earendil-works/pi-coding-agent";
13
- import { openTestSession } from "../testing/session.testing.ts";
14
-
15
- interface CallableTool extends Tool {
16
- prepareArguments?(args: unknown): unknown;
17
- execute(
18
- toolCallId: string,
19
- params: unknown,
20
- signal: AbortSignal | undefined,
21
- onUpdate: unknown,
22
- ctx: unknown,
23
- ): Promise<unknown>;
24
- }
25
-
26
- export interface ToolCallOptions {
27
- toolCallId?: string;
28
- signal?: AbortSignal;
29
- onUpdate?: unknown;
30
- ctx?: unknown;
31
- }
32
-
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"]>;
39
- export async function callTool(tool: CallableTool, args: unknown, options: ToolCallOptions = {}) {
40
- const toolCallId = options.toolCallId ?? "test";
41
- const prepared = tool.prepareArguments ? tool.prepareArguments(args) : args;
42
- const validated: unknown = validateToolArguments(tool, {
43
- type: "toolCall",
44
- id: toolCallId,
45
- name: tool.name,
46
- // Pi owns shape checking and coercion at this external boundary.
47
- arguments: prepared as ToolCall["arguments"],
48
- });
49
- return tool.execute(toolCallId, validated, options.signal, options.onUpdate, options.ctx);
50
- }
51
-
52
- /** Create Pi's tool context without loading user credentials or contacting a provider. */
53
- export async function createToolContext(
54
- cwd: string,
55
- t: TestContext,
56
- mode: ExtensionToolContext["mode"] = "json",
57
- ) {
58
- const { session } = await openTestSession(t, { cwd, tools: [] });
59
- session.extensionRunner.setUIContext(undefined, mode);
60
- return session.extensionRunner.createToolContext("test", undefined);
61
- }
@@ -1,59 +0,0 @@
1
- import { mkdtempSync, rmSync } from "node:fs";
2
- import { join } from "node:path";
3
- import { tmpdir } from "node:os";
4
- import { loadConfig, type HashlineEditConfig } from "./config.ts";
5
- import { outputBudgetsFor, type OutputBudgetProvider } from "./budgets.ts";
6
- import { makeReadOverride as read } from "./read-tool.ts";
7
- import { makeGrepOverride as grep } from "./grep-tool.ts";
8
- import { makeEditOverride as edit } from "./edit-tool.ts";
9
- import { makeReplaceTool as replace } from "./replace-tool.ts";
10
- import { makeWriteOverride as write } from "./write-tool.ts";
11
- import type { MutationToolEnvironment } from "./mutation-runner.ts";
12
-
13
- // The runner isolates global settings; create an empty project root for schema defaults.
14
- const configRoot = mkdtempSync(join(tmpdir(), "hashline-default-config-"));
15
- export const DEFAULT_CONFIG = (() => {
16
- try {
17
- return loadConfig(configRoot);
18
- } finally {
19
- rmSync(configRoot, { recursive: true, force: true });
20
- }
21
- })();
22
- export const DEFAULT_OUTPUT_BUDGETS = outputBudgetsFor(undefined);
23
- export const defaultOutputBudgets = () => outputBudgetsFor(undefined);
24
-
25
- function toolEnvironment(
26
- cwd: string,
27
- config: HashlineEditConfig,
28
- budgets: OutputBudgetProvider,
29
- ): { cwd: string; config: HashlineEditConfig; budgets: OutputBudgetProvider } {
30
- return { cwd, config, budgets };
31
- }
32
-
33
- export const makeReadOverride = (
34
- cwd: string,
35
- config: HashlineEditConfig,
36
- budgets = defaultOutputBudgets,
37
- ) => read(toolEnvironment(cwd, config, budgets));
38
- export const makeGrepOverride = (
39
- cwd: string,
40
- config: HashlineEditConfig,
41
- budgets = defaultOutputBudgets,
42
- ) => grep(toolEnvironment(cwd, config, budgets));
43
- export const makeEditOverride = (
44
- cwd: string,
45
- config: HashlineEditConfig,
46
- fusion: MutationToolEnvironment["fusion"] = undefined,
47
- budgets = defaultOutputBudgets,
48
- ) => edit({ ...toolEnvironment(cwd, config, budgets), fusion });
49
- export const makeReplaceTool = (
50
- cwd: string,
51
- config: HashlineEditConfig,
52
- fusion: MutationToolEnvironment["fusion"] = undefined,
53
- budgets = defaultOutputBudgets,
54
- ) => replace({ ...toolEnvironment(cwd, config, budgets), fusion });
55
- export const makeWriteOverride = (
56
- cwd: string,
57
- fusion: MutationToolEnvironment["fusion"] = undefined,
58
- budgets = defaultOutputBudgets,
59
- ) => write({ ...toolEnvironment(cwd, DEFAULT_CONFIG, budgets), fusion });