@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,111 +0,0 @@
1
- import { makeMockGrep } from "../pi/grep-rg.testing.ts";
2
- import assert from "node:assert/strict";
3
- import { mkdtemp, rm, truncate, writeFile } from "node:fs/promises";
4
- import { tmpdir } from "node:os";
5
- import { join } from "node:path";
6
- import { test } from "node:test";
7
- import { formatByteSize } from "../pi/budgets.ts";
8
- const { DEFAULT_CONFIG, makeGrepOverride } = await import("../pi/tool-factories.testing.ts");
9
- const MAX_MULTILINE_SEARCH_BYTES = 64 * 1024 * 1024;
10
- const { MAX_UNNARROWED_SCAN_BYTES } = await import("../pi/grep-candidates.ts");
11
-
12
- import { OUTCOME_NEXT } from "../pi/report-schema.ts";
13
- import { reportOf } from "../pi/report.ts";
14
- const { grepCounts } = await import("../pi/grep-output.testing.ts");
15
- import { callTool } from "../pi/tool-call.testing.ts";
16
-
17
- test("repeated all-file candidates → count each file once toward the scan budget", async (t) => {
18
- const directory = await mkdtemp(join(tmpdir(), "hl-grep-repeated-scan-"));
19
- t.after(() => rm(directory, { recursive: true, force: true }));
20
- const padding = join(directory, "a.bin");
21
- const fixture = join(directory, "b.txt");
22
- await writeFile(padding, "");
23
- await truncate(padding, MAX_MULTILINE_SEARCH_BYTES);
24
- await writeFile(fixture, "ab\n");
25
- const repeats = Math.ceil(MAX_UNNARROWED_SCAN_BYTES / MAX_MULTILINE_SEARCH_BYTES);
26
- const result = await callTool(makeGrepOverride(directory, DEFAULT_CONFIG), {
27
- path: [...Array<string>(repeats).fill(padding), fixture],
28
- pattern: ".",
29
- literal: false,
30
- multiline: true,
31
- outputMode: "files",
32
- });
33
- assert.equal(result.isError, undefined);
34
- assert.deepEqual(result.content[0], { type: "text", text: "b.txt" });
35
- assert.equal(reportOf(result, "grep")?.scanLimit, undefined);
36
- });
37
-
38
- test("all-file candidates exceed the scan budget → stop listing and retain scan facts with or without matches", async (t) => {
39
- const directory = await mkdtemp(join(tmpdir(), "hl-grep-scan-budget-"));
40
- t.after(() => rm(directory, { recursive: true, force: true }));
41
- const scanLimitNext = OUTCOME_NEXT.find(([fact]) => fact === "scanLimit")?.[1];
42
- assert.ok(scanLimitNext);
43
- const padding: string[] = [];
44
- // NUL files consume real scan bytes without building large regex inputs or exceeding the per-file cap.
45
- for (let remaining = MAX_UNNARROWED_SCAN_BYTES; remaining > 0; ) {
46
- const size = Math.min(remaining, MAX_MULTILINE_SEARCH_BYTES);
47
- const path = join(directory, `padding-${padding.length}.bin`);
48
- await writeFile(path, "");
49
- await truncate(path, size);
50
- padding.push(path);
51
- remaining -= size;
52
- }
53
- const fixture = join(directory, "fixture.txt");
54
- const blocked = join(directory, "beyond-budget.txt");
55
- const unlisted = join(directory, "unlisted.txt");
56
- await writeFile(blocked, "abc\n");
57
- await writeFile(unlisted, "abc\n");
58
- const paths = [fixture, ...padding, blocked, unlisted];
59
- for (const scenario of [
60
- { name: "matches", source: "abc\n", matches: 1, stderr: "" },
61
- { name: "zero matches", source: "xxx\n", matches: 0, stderr: "" },
62
- {
63
- name: "zero matches with listing diagnostics",
64
- source: "xxx\n",
65
- matches: 0,
66
- stderr: "listing interrupted",
67
- },
68
- ]) {
69
- await t.test(scenario.name, async () => {
70
- await writeFile(fixture, scenario.source);
71
- const offered: string[] = [];
72
- let stopped = false;
73
- const tool = makeMockGrep(directory, DEFAULT_CONFIG, {
74
- runRgLines: async () => assert.fail("multiline candidates must use file listing"),
75
- runRgPaths: async (_args, _signal, onFile) => {
76
- for (const path of paths) {
77
- offered.push(path);
78
- if (!(await onFile(path))) {
79
- stopped = true;
80
- break;
81
- }
82
- }
83
- return { code: scenario.stderr ? 2 : 0, stderr: scenario.stderr, stopped };
84
- },
85
- });
86
- const result = await callTool(tool, {
87
- path: directory,
88
- pattern: "[^x\\s]{3}\\s",
89
- literal: false,
90
- multiline: true,
91
- });
92
- assert.equal(stopped, true);
93
- assert.deepEqual(offered, [fixture, ...padding, blocked]);
94
- const report = reportOf(result, "grep");
95
- assert.ok(report);
96
- assert.equal(report.scanLimit, formatByteSize(MAX_UNNARROWED_SCAN_BYTES));
97
- if (scenario.stderr) {
98
- assert.equal(result.isError, true);
99
- assert.equal(report.error, "SEARCH_INCOMPLETE");
100
- assert.match(report.diagnostics ?? "", /listing interrupted/);
101
- } else {
102
- assert.equal(result.isError, undefined);
103
- assert.equal(grepCounts(result).matches, scenario.matches);
104
- assert.equal(report.diagnostics, undefined);
105
- assert.equal(report.next, scanLimitNext);
106
- assert.equal(result.content[0].type, "text");
107
- if (scenario.matches) assert.match(result.content[0].text, /fixture\.txt/);
108
- }
109
- });
110
- }
111
- });
@@ -1,199 +0,0 @@
1
- import { searchWithMockRg } from "../pi/grep-rg.testing.ts";
2
- import assert from "node:assert/strict";
3
- import { mkdtemp, rm, writeFile } from "node:fs/promises";
4
- import { tmpdir } from "node:os";
5
- import { join, resolve } from "node:path";
6
- import { test } from "node:test";
7
- import { searchText, type GrepQuery } from "../core/search.ts";
8
- import type { GrepFileMatch } from "../pi/grep-search.ts";
9
- import { runRgLines, runRgPaths } from "../pi/rg-process.ts";
10
- import { fileCandidateArgs } from "../pi/grep-rg.testing.ts";
11
- import { lineCandidatePatterns } from "../pi/rg-regex.ts";
12
-
13
- import { REGEX_TRANSLATION_CORPUS } from "../testing/regex-translation-corpus.ts";
14
- import { unsupportedByHost } from "../testing/regex-host.testing.ts";
15
-
16
- const timeoutMs = 10_000;
17
- const sorted = (files: readonly Pick<GrepFileMatch, "filePath" | "rows">[]) =>
18
- files
19
- .flatMap(({ filePath, rows }) => rows.map((row) => ({ ...row, filePath })))
20
- .sort((a, b) => a.filePath.localeCompare(b.filePath) || a.lineNumber - b.lineNumber);
21
-
22
- test("upstream regex witnesses × LF/CRLF/malformed bytes → sound candidates, intended selectivity and exact JS results", {
23
- timeout: 120_000,
24
- }, async (t) => {
25
- const directory = await mkdtemp(join(tmpdir(), "hl-regex-upstream-"));
26
- t.after(() => rm(directory, { recursive: true, force: true }));
27
- for (const [index, example] of REGEX_TRANSLATION_CORPUS.entries()) {
28
- await t.test(
29
- `${example.pattern.slice(0, 90)} /${example.ignoreCase ? "mi" : "m"}`,
30
- { skip: unsupportedByHost([example.pattern], example.ignoreCase ? "mi" : "m") },
31
- async () => {
32
- const query: GrepQuery = {
33
- patterns: [example.pattern],
34
- ignoreCase: example.ignoreCase,
35
- literal: false,
36
- multiline: false,
37
- };
38
- for (const value of example.hits)
39
- assert.ok(
40
- searchText({ source: value, query, limit: 100 }).lines.length,
41
- `${example.source}: ${JSON.stringify(value)}`,
42
- );
43
- for (const value of example.misses)
44
- assert.equal(
45
- searchText({ source: value, query, limit: 100 }).lines.length,
46
- 0,
47
- `${example.source}: ${JSON.stringify(value)}`,
48
- );
49
- const inputs = [];
50
- for (const [name, separator] of [
51
- ["lf", "\n"],
52
- ["crlf", "\r\n"],
53
- ]) {
54
- const source = [
55
- ...example.hits,
56
- ...example.misses,
57
- "a\rb",
58
- "\u0558",
59
- "éÉΣςKſ𐐀𐐨😀",
60
- "Σ",
61
- "a�b",
62
- "",
63
- ].join(separator);
64
- const bytes = Buffer.concat([
65
- Buffer.from(source),
66
- Buffer.from([0x80, 0xc3, 0xe2, 0x82, 0xed, 0xa0, 0x80, 0xf0, 0x9f, 0x98, 0xff]),
67
- Buffer.from(`${separator}tail\r`),
68
- ]);
69
- const filePath = join(directory, `${index}-${name}.txt`);
70
- await writeFile(filePath, bytes);
71
- inputs.push({ bytes, filePath });
72
- }
73
- const candidates = new Map<string, readonly number[] | undefined>();
74
- const result = await searchWithMockRg({
75
- backend: {
76
- runRgPaths: async () => assert.fail("unexpected file fallback"),
77
- runRgLines: (args, signal, maxLines, onFile) =>
78
- runRgLines(args, signal, maxLines, (path, lines) => {
79
- candidates.set(resolve(path), lines);
80
- return onFile(path, lines);
81
- }),
82
- },
83
- scope: {
84
- globs: [],
85
- searchPaths: inputs.map((input) => input.filePath),
86
- },
87
- query,
88
- limit: 1000,
89
- timeoutMs,
90
- signal: AbortSignal.timeout(timeoutMs),
91
- });
92
- const expected = inputs.map(({ bytes, filePath }) => {
93
- const native = searchText({ source: bytes.toString("utf8"), query, limit: 1000 });
94
- for (const row of native.lines)
95
- assert.ok(
96
- candidates.get(filePath)?.includes(row.lineNumber),
97
- `missing candidate ${filePath}:${row.lineNumber}`,
98
- );
99
- if (example.rejectCandidates)
100
- for (let offset = 0; offset < example.misses.length; offset++) {
101
- const line = example.hits.length + offset + 1;
102
- assert.equal(
103
- candidates.get(filePath)?.includes(line) ?? false,
104
- false,
105
- `unfiltered ${JSON.stringify(example.misses[offset])}`,
106
- );
107
- }
108
- return { filePath, rows: native.lines };
109
- });
110
- assert.deepEqual(result.warnings, []);
111
- assert.deepEqual(sorted(result.files), sorted(expected));
112
- },
113
- );
114
- }
115
- });
116
-
117
- test("real rg AND/OR file prefilter → broad candidates retain exact JS results", {
118
- skip: unsupportedByHost(["(?s:foo.*bar|baz.*qux)"], "m"),
119
- }, async (t) => {
120
- const directory = await mkdtemp(join(tmpdir(), "hl-regex-conjunction-"));
121
- t.after(() => rm(directory, { recursive: true, force: true }));
122
- const fixtures = ["foo\nbar", "baz\nqux", "foo\nqux", "baz\nbar", "foo", "bar", "unrelated"];
123
- const paths: string[] = [];
124
- for (const [index, source] of fixtures.entries()) {
125
- const path = join(directory, `${index}.txt`);
126
- await writeFile(path, source);
127
- paths.push(path);
128
- }
129
- const query: GrepQuery = {
130
- patterns: ["(?s:foo.*bar|baz.*qux)"],
131
- ignoreCase: false,
132
- literal: false,
133
- multiline: true,
134
- };
135
- const candidates: string[] = [];
136
- const listing = await runRgPaths(
137
- [...(await fileCandidateArgs(query)), "--null", "--", directory],
138
- AbortSignal.timeout(timeoutMs),
139
- (path) => {
140
- candidates.push(resolve(path));
141
- return true;
142
- },
143
- );
144
- assert.equal(listing.code, 0);
145
- assert.equal(listing.stderr, "");
146
- assert.deepEqual(candidates.sort(), [paths[0], paths[1], paths[2], paths[3], paths[4]].sort());
147
- const result = await searchWithMockRg({
148
- backend: { runRgPaths, runRgLines },
149
- scope: { globs: [], searchPaths: [directory] },
150
- query,
151
- limit: 100,
152
- timeoutMs,
153
- });
154
- assert.deepEqual(result.warnings, []);
155
- assert.deepEqual(
156
- sorted(result.files),
157
- sorted(
158
- fixtures.map((source, index) => ({
159
- filePath: paths[index],
160
- rows: searchText({ source, query, limit: 100 }).lines,
161
- })),
162
- ),
163
- );
164
- });
165
-
166
- test("oversized line translation → file prefilter fallback preserves JS results", async (t) => {
167
- const directory = await mkdtemp(join(tmpdir(), "hl-regex-budget-"));
168
- t.after(() => rm(directory, { recursive: true, force: true }));
169
- const pattern = "a".repeat(30_000);
170
- const query: GrepQuery = {
171
- patterns: [pattern],
172
- ignoreCase: false,
173
- literal: true,
174
- multiline: false,
175
- };
176
- assert.equal(lineCandidatePatterns(query), undefined);
177
- const path = join(directory, "long.txt");
178
- await writeFile(path, pattern);
179
- let filePasses = 0;
180
- const result = await searchWithMockRg({
181
- backend: {
182
- runRgPaths: (...args) => {
183
- filePasses++;
184
- return runRgPaths(...args);
185
- },
186
- runRgLines: async () => assert.fail("translation budget must select file prefilter"),
187
- },
188
- scope: { globs: [], searchPaths: [path] },
189
- query,
190
- limit: 10,
191
- timeoutMs,
192
- });
193
- assert.ok(filePasses > 0);
194
- assert.deepEqual(result.warnings, []);
195
- assert.deepEqual(
196
- sorted(result.files),
197
- sorted([{ filePath: path, rows: searchText({ source: pattern, query, limit: 10 }).lines }]),
198
- );
199
- });
@@ -1,70 +0,0 @@
1
- import { test } from "node:test";
2
- import assert from "node:assert/strict";
3
- import { mkdtemp, open, rm, writeFile } from "node:fs/promises";
4
- import { tmpdir } from "node:os";
5
- import { join } from "node:path";
6
- import { makeReadOverride } from "../pi/tool-factories.testing.ts";
7
- import { makeGrepOverride } from "../pi/tool-factories.testing.ts";
8
- import { computeLineHash } from "../core/hash.ts";
9
- import { callTool } from "../pi/tool-call.testing.ts";
10
- import { DEFAULT_CONFIG } from "../pi/tool-factories.testing.ts";
11
-
12
- const call = (tool: any, params: any) => callTool(tool, params, { toolCallId: "large-text" });
13
-
14
- test("read and line-based grep retain anchors on LF and CRLF files over 100 MiB", async () => {
15
- const directory = await mkdtemp(join(tmpdir(), "hashline-large-text-"));
16
- try {
17
- const read = makeReadOverride(directory, DEFAULT_CONFIG);
18
- const grep = makeGrepOverride(directory, DEFAULT_CONFIG);
19
- for (const ending of ["\n", "\r\n"]) {
20
- const path = join(directory, "large.txt");
21
- const handle = await open(path, "w");
22
- const line = "x".repeat(1024 - ending.length) + ending;
23
- const block = Buffer.from(line.repeat(1024));
24
- try {
25
- await handle.writeFile("needle" + ending);
26
- for (let i = 0; i < 101; i++) await handle.writeFile(block);
27
- await handle.writeFile("tail" + ending);
28
- } finally {
29
- await handle.close();
30
- }
31
- const first: any = await call(read, { path, limit: 1 });
32
- assert.match(first.content[0].text, /103426 lines/);
33
- assert.ok(first.content[0].text.includes(`1#${computeLineHash(1, "needle", 4)}│needle`));
34
- const last: any = await call(read, { path, offset: 103426, limit: 1 });
35
- assert.ok(last.content[0].text.includes(`103426#${computeLineHash(103426, "tail", 4)}│tail`));
36
- const result: any = await call(grep, { path, pattern: "needle", literal: true });
37
- assert.ok(result.content[0].text.includes(`1#${computeLineHash(1, "needle", 4)}│needle`));
38
- assert.doesNotMatch(result.content[0].text, /Search incomplete/);
39
- const tail: Awaited<ReturnType<typeof grep.execute>> = await callTool(grep, {
40
- path,
41
- pattern: "(?<=ta)il",
42
- literal: false,
43
- });
44
- assert.equal(tail.isError, undefined);
45
- const body = tail.content[0];
46
- assert.ok(body.type === "text");
47
- assert.ok(body.text.includes(`103426#${computeLineHash(103426, "tail", 4)}│tail`));
48
- }
49
- } finally {
50
- await rm(directory, { recursive: true, force: true });
51
- }
52
- });
53
-
54
- test("CRLF snapshots normalize terminators split across read chunks and preserve standalone CR", async () => {
55
- const directory = await mkdtemp(join(tmpdir(), "hashline-snapshot-boundary-"));
56
- try {
57
- const path = join(directory, "boundary.txt");
58
- await writeFile(path, "x".repeat(65535) + "\r\nneedle\r\nstandalone\r");
59
- const grep = makeGrepOverride(directory, DEFAULT_CONFIG);
60
- const result: any = await call(grep, {
61
- path,
62
- pattern: ["needle", "standalone\r"],
63
- literal: true,
64
- });
65
- assert.ok(result.content[0].text.includes(`2#${computeLineHash(2, "needle", 4)}│needle`));
66
- assert.ok(result.content[0].text.includes(`3#${computeLineHash(3, "standalone\r", 4)}│`));
67
- } finally {
68
- await rm(directory, { recursive: true, force: true });
69
- }
70
- });
@@ -1,186 +0,0 @@
1
- import assert from "node:assert/strict";
2
- import { test } from "node:test";
3
- import { writeFile } from "node:fs/promises";
4
- import { join } from "node:path";
5
- import hashlineEdit from "../index.ts";
6
- import { callTool } from "../pi/tool-call.testing.ts";
7
- import { outputBudgetsFor } from "../pi/budgets.ts";
8
- import { reportOf } from "../pi/report.ts";
9
- import type { Report } from "../pi/report-schema.ts";
10
- import { openTestSession, responseStream } from "../testing/session.testing.ts";
11
-
12
- // Budget invalidation relies on Pi publishing the new model before tool preparation.
13
- test("model selection → exposes the new limit and invalidates only on a selection change", async (t) => {
14
- const observations: { source: string; id: string | undefined; limit: number | undefined }[] = [];
15
- const fixture = await openTestSession(t, {
16
- tools: [],
17
- configure(pi) {
18
- pi.on("session_start", (_event, ctx) => {
19
- observations.push({ source: "start", id: ctx.model?.id, limit: ctx.model?.contextWindow });
20
- });
21
- pi.on("model_select", (event, ctx) => {
22
- assert.equal(ctx.model?.id, event.model.id);
23
- assert.equal(ctx.model?.contextWindow, event.model.contextWindow);
24
- observations.push({
25
- source: event.source,
26
- id: event.model.id,
27
- limit: event.model.contextWindow,
28
- });
29
- });
30
- },
31
- });
32
- assert.equal(observations.length, 1);
33
- assert.equal(observations[0].limit, fixture.model.contextWindow);
34
- const small = { ...fixture.model, id: "small", contextWindow: 65_536 };
35
- const large = { ...fixture.model, id: "large", contextWindow: 1_048_576 };
36
- fixture.session.modelRuntime.registerProvider(fixture.model.provider, {
37
- api: "openai-completions",
38
- baseUrl: "https://unused.invalid",
39
- apiKey: "local-test-placeholder",
40
- models: [small, large],
41
- });
42
- await fixture.session.setModel(small);
43
- await fixture.session.setModel(small);
44
- assert.deepEqual(observations.slice(1), [
45
- { source: "set", id: "small", limit: small.contextWindow },
46
- ]);
47
- fixture.session.setScopedModels([{ model: small }, { model: large }]);
48
- await fixture.session.cycleModel();
49
- assert.deepEqual(observations.at(-1), {
50
- source: "cycle",
51
- id: "large",
52
- limit: large.contextWindow,
53
- });
54
- const ctx = fixture.session.extensionRunner.createToolContext("budget-probe", undefined);
55
- assert.equal(ctx.model?.contextWindow, large.contextWindow);
56
- await fixture.session.setModel(small);
57
- assert.equal(ctx.model?.contextWindow, small.contextWindow);
58
- });
59
-
60
- test("model capacity changes → read and grep grow and shrink without re-registering tools", async (t) => {
61
- const { session, cwd, model } = await openTestSession(t, {
62
- tools: ["read", "grep"],
63
- configure: (pi) => hashlineEdit(pi),
64
- });
65
- const path = join(cwd, "large-row.txt");
66
- const smallBudget = outputBudgetsFor(65_536);
67
- const largeBudget = outputBudgetsFor(1_048_576);
68
- const text = "中文🙂".repeat(
69
- Math.floor((smallBudget.readBytes + largeBudget.readBytes) / (2 * Buffer.byteLength("中文🙂"))),
70
- );
71
- await writeFile(path, text);
72
- const tool = session.getToolDefinition("read");
73
- assert.ok(tool);
74
- const ctx = session.extensionRunner.createToolContext("read-budget", undefined);
75
- await session.setModel({ ...model, id: "small", contextWindow: 65_536 });
76
- const small = await callTool(tool, { path }, { ctx });
77
- const smallReport = reportOf(small, "read");
78
- assert.ok(smallReport?.lineTooLong);
79
- await session.setModel({ ...model, id: "large", contextWindow: 1_048_576 });
80
- const large = await callTool(tool, { path }, { ctx });
81
- const largeReport = reportOf(large, "read");
82
- assert.ok(largeReport);
83
- assert.equal(largeReport.lineTooLong, undefined);
84
- assert.equal(large.content[0].type, "text");
85
- assert.ok(large.content[0].text.includes(text));
86
- await session.setModel({ ...model, id: "small", contextWindow: 65_536 });
87
- const smallAgain = await callTool(tool, { path }, { ctx });
88
- assert.equal(reportOf(smallAgain, "read")?.lineTooLong, smallReport?.lineTooLong);
89
- const grep = session.getToolDefinition("grep");
90
- assert.ok(grep);
91
- const smallSearch = await callTool(grep, { path, pattern: "中文", literal: true }, { ctx });
92
- await session.setModel({ ...model, id: "large", contextWindow: 1_048_576 });
93
- const largeSearch = await callTool(grep, { path, pattern: "中文", literal: true }, { ctx });
94
- assert.equal(
95
- reportOf(smallSearch, "grep")?.linePreviewLimit,
96
- outputBudgetsFor(65_536).grepPreviewUnits,
97
- );
98
- assert.equal(
99
- reportOf(largeSearch, "grep")?.linePreviewLimit,
100
- outputBudgetsFor(1_048_576).grepPreviewUnits,
101
- );
102
- assert.equal(largeSearch.content[0].type, "text");
103
- assert.equal(smallSearch.content[0].type, "text");
104
- assert.ok(largeSearch.content[0].text.length > smallSearch.content[0].text.length);
105
- assert.ok(!largeSearch.content[0].text.includes("\uFFFD"));
106
- });
107
-
108
- test("model switches before argument preparation → rejection uses the new budget without execution", async (t) => {
109
- const { session, model } = await openTestSession(t, {
110
- tools: ["edit"],
111
- configure: (pi) => hashlineEdit(pi),
112
- });
113
- const tool = session.getToolDefinition("edit");
114
- const prepare = tool?.prepareArguments;
115
- assert.ok(prepare);
116
- const properties: unknown = Reflect.get(tool.parameters, "properties");
117
- assert.ok(properties && typeof properties === "object");
118
- const steps: unknown = Reflect.get(properties, "steps");
119
- assert.ok(steps && typeof steps === "object");
120
- const maxEdits: unknown = Reflect.get(steps, "maxItems");
121
- assert.ok(typeof maxEdits === "number");
122
- const args = {
123
- path: "never-opened.txt",
124
- steps: Array.from({ length: maxEdits }, () => ({
125
- action: "append",
126
- lines: Array(4).fill("\ud800"),
127
- })),
128
- };
129
- const reports: Report[] = [];
130
- for (const [id, contextWindow] of [
131
- ["small", 65_536],
132
- ["large", 1_048_576],
133
- ] as const) {
134
- await session.setModel({ ...model, id, contextWindow });
135
- assert.throws(
136
- () => prepare(args),
137
- (error: unknown) => {
138
- assert.ok(error instanceof Error);
139
- const budget = outputBudgetsFor(contextWindow);
140
- assert.ok(Buffer.byteLength(error.message) <= budget.blockBytes);
141
- const report = reportOf({ content: [{ type: "text", text: error.message }] }, "edit");
142
- assert.ok(report?.issues);
143
- assert.equal(report.issues.length + (report.omittedIssues ?? 0), args.steps.length * 4);
144
- reports.push(report);
145
- return true;
146
- },
147
- );
148
- }
149
- assert.ok(reports[0].omittedIssues);
150
- assert.equal(reports[1].omittedIssues, undefined);
151
- });
152
-
153
- test("headless SDK reload → tool results still use the selected model's budget", async (t) => {
154
- const { session, cwd, model } = await openTestSession(t, {
155
- tools: ["read"],
156
- configure: (pi) => hashlineEdit(pi),
157
- });
158
- const capacity = 16_384;
159
- const selected = { ...model, contextWindow: capacity };
160
- await session.setModel(selected);
161
- await session.reload();
162
- const path = "long-line.txt";
163
- await writeFile(join(cwd, path), "x".repeat(outputBudgetsFor(capacity).readBytes * 2));
164
- let requests = 0;
165
- session.agent.streamFunction = () => {
166
- const first = requests++ === 0;
167
- return responseStream(
168
- selected,
169
- first
170
- ? {
171
- stopReason: "toolUse",
172
- content: [
173
- { type: "toolCall", id: "read-after-reload", name: "read", arguments: { path } },
174
- ],
175
- }
176
- : { stopReason: "stop", content: [{ type: "text", text: "Done." }] },
177
- );
178
- };
179
- await session.prompt("Read the fixture after reload.");
180
- const result = session.agent.state.messages.find(
181
- (message) => message.role === "toolResult" && message.toolCallId === "read-after-reload",
182
- );
183
- assert.ok(result?.role === "toolResult");
184
- assert.equal(result.isError, false);
185
- assert.ok(reportOf(result, "read")?.lineTooLong);
186
- });
@@ -1,30 +0,0 @@
1
- import { execFile as execFileCallback } from "node:child_process";
2
- import { mkdtemp, rm, symlink } from "node:fs/promises";
3
- import { tmpdir } from "node:os";
4
- import { join } from "node:path";
5
- import { test } from "node:test";
6
- import { promisify } from "node:util";
7
- import { fileURLToPath } from "node:url";
8
- import { testEnvironment } from "../testing/process.testing.ts";
9
-
10
- const execFile = promisify(execFileCallback);
11
-
12
- test("FIFO mutation targets → reject without waiting for a writer, including through a symlink", {
13
- skip: process.platform === "win32" ? "POSIX FIFO behavior" : false,
14
- }, async (t) => {
15
- const directory = await mkdtemp(join(tmpdir(), "hashline-fifo-"));
16
- t.after(() => rm(directory, { recursive: true, force: true }));
17
- const fifo = join(directory, "pipe");
18
- await execFile("mkfifo", [fifo]);
19
- await symlink("pipe", join(directory, "alias"));
20
- // Isolate a blocking open so a regression cannot leave the parent runner stuck.
21
- await execFile(
22
- process.execPath,
23
- [fileURLToPath(new URL("./mutation-file-types.testing.ts", import.meta.url)), directory],
24
- {
25
- env: testEnvironment(directory),
26
- timeout: 10_000,
27
- killSignal: "SIGKILL",
28
- },
29
- );
30
- });
@@ -1,33 +0,0 @@
1
- /** Isolate a FIFO open so a regression cannot stall the parent runner's I/O threads. */
2
- import assert from "node:assert/strict";
3
- import { join } from "node:path";
4
- import { makeEditOverride } from "../pi/tool-factories.testing.ts";
5
- import { makeReplaceTool } from "../pi/tool-factories.testing.ts";
6
- import { DEFAULT_CONFIG } from "../pi/tool-factories.testing.ts";
7
- import { callTool } from "../pi/tool-call.testing.ts";
8
- import { expectToolFailure } from "../pi/report-failure.testing.ts";
9
-
10
- const directory = process.argv[2];
11
- assert.ok(directory);
12
- const cases = [
13
- {
14
- tool: makeEditOverride(directory, DEFAULT_CONFIG),
15
- args: { steps: [{ action: "append", lines: ["after"] }] },
16
- },
17
- {
18
- tool: makeReplaceTool(directory, DEFAULT_CONFIG),
19
- args: { replacements: [{ literal: true, find: "before", replace: "after" }] },
20
- },
21
- ];
22
- for (const path of ["pipe", "alias"]) {
23
- for (const { tool, args } of cases) {
24
- await expectToolFailure(
25
- callTool(tool, { path: join(directory, path), ...args }),
26
- "NOT_REGULAR_FILE",
27
- (report) => {
28
- assert.match(report.message ?? "", /not a regular file/);
29
- assert.equal(report.publication, "NOT_PUBLISHED");
30
- },
31
- );
32
- }
33
- }
@@ -1,19 +0,0 @@
1
- import { access } from "node:fs/promises";
2
- import { join } from "node:path";
3
- import { fileURLToPath } from "node:url";
4
- import { test } from "node:test";
5
- import { installedExtension } from "../testing/installation.testing.ts";
6
- import { runTestProcess } from "../testing/process.testing.ts";
7
-
8
- for (const source of ["source", "packed"] as const) {
9
- test(`${source} installation without devDependencies → real Pi workflow and argument diagnostics`, async (t) => {
10
- const installation = await installedExtension(t, source);
11
- if (source === "packed") await access(join(installation.packageDir, "THIRD_PARTY_NOTICES.md"));
12
- await runTestProcess(
13
- process.execPath,
14
- [fileURLToPath(new URL("./npm-package.testing.ts", import.meta.url)), installation.entry],
15
- installation.root,
16
- installation.agentDir,
17
- );
18
- });
19
- }