@criogaid/pi-hashline-edit 0.6.0 → 0.7.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 (148) hide show
  1. package/README.md +161 -304
  2. package/THIRD_PARTY_NOTICES.md +80 -0
  3. package/package.json +10 -6
  4. package/src/core/AGENTS.md +20 -0
  5. package/src/core/apply.test.ts +189 -60
  6. package/src/core/apply.ts +110 -74
  7. package/src/core/case-fold.test.ts +40 -0
  8. package/src/core/case-fold.ts +81 -0
  9. package/src/core/character-set.test.ts +103 -0
  10. package/src/core/character-set.ts +170 -0
  11. package/src/core/errors.test.ts +23 -0
  12. package/src/core/errors.ts +70 -4
  13. package/src/core/lines.ts +7 -0
  14. package/src/core/regex.ts +21 -0
  15. package/src/core/replace-schema.ts +34 -0
  16. package/src/core/replace.ts +37 -54
  17. package/src/core/search-analysis.test.ts +199 -0
  18. package/src/core/search-analysis.ts +375 -0
  19. package/src/core/search-matrix.test.ts +64 -0
  20. package/src/core/search-matrix.testing.ts +183 -0
  21. package/src/core/search-schema.ts +18 -0
  22. package/src/core/search.test.ts +145 -0
  23. package/src/core/search.ts +119 -0
  24. package/src/core/text.test.ts +16 -8
  25. package/src/core/text.ts +26 -6
  26. package/src/core/types.ts +16 -11
  27. package/src/index.ts +25 -15
  28. package/src/integration/config-registration.test.ts +30 -24
  29. package/src/integration/forget-grep.test.ts +52 -2
  30. package/src/integration/fusion-dispatch.test.ts +21 -105
  31. package/src/integration/grep-errors.test.ts +50 -0
  32. package/src/integration/grep-flags.test.ts +280 -0
  33. package/src/integration/grep-js-completeness.test.ts +208 -0
  34. package/src/integration/grep-line-candidates.test.ts +233 -0
  35. package/src/integration/grep-matrix.test.ts +121 -0
  36. package/src/integration/grep-path-matrix.test.ts +132 -0
  37. package/src/integration/grep-prefilter-coverage.test.ts +189 -0
  38. package/src/integration/grep-regex.test.ts +410 -0
  39. package/src/integration/grep-rg.test.ts +220 -402
  40. package/src/integration/grep-scan-budget.test.ts +89 -0
  41. package/src/integration/grep-translation.test.ts +206 -0
  42. package/src/integration/large-text.test.ts +57 -1
  43. package/src/integration/model-budget-lifecycle.test.ts +128 -0
  44. package/src/integration/mutation-file-types.test.ts +12 -25
  45. package/src/integration/mutation-file-types.testing.ts +33 -0
  46. package/src/integration/npm-package.test.ts +17 -0
  47. package/src/integration/npm-package.testing.ts +123 -0
  48. package/src/integration/publication-read-changes.test.ts +344 -0
  49. package/src/integration/read-changes.test.ts +98 -0
  50. package/src/integration/replace-package.test.ts +17 -36
  51. package/src/integration/replace-package.testing.ts +33 -0
  52. package/src/integration/replace-worker-boundary.test.ts +107 -0
  53. package/src/integration/report-replay.test.ts +90 -0
  54. package/src/integration/utf8-errors.test.ts +46 -0
  55. package/src/pi/AGENTS.md +55 -0
  56. package/src/pi/action-fusion.test.ts +253 -103
  57. package/src/pi/action-fusion.ts +116 -290
  58. package/src/pi/anchor-format.ts +9 -0
  59. package/src/pi/argument-diagnostics.ts +478 -0
  60. package/src/pi/argument-error.testing.ts +43 -0
  61. package/src/pi/argument-error.ts +78 -0
  62. package/src/pi/argument-format.test.ts +208 -0
  63. package/src/pi/argument-validation.test.ts +742 -45
  64. package/src/pi/argument-validation.ts +56 -59
  65. package/src/pi/budgets.ts +45 -16
  66. package/src/pi/codemode.test.ts +96 -0
  67. package/src/pi/config.test.ts +14 -10
  68. package/src/pi/config.ts +21 -7
  69. package/src/pi/diagnostic-buffer.test.ts +52 -16
  70. package/src/pi/diagnostic-buffer.ts +11 -14
  71. package/src/pi/directory-sync.test.ts +4 -1
  72. package/src/pi/edit-tool.ts +100 -93
  73. package/src/pi/error-text.ts +39 -16
  74. package/src/pi/execute.test.ts +362 -315
  75. package/src/pi/extension-loading.test.ts +14 -0
  76. package/src/pi/extension-loading.testing.ts +3 -0
  77. package/src/pi/failure-context.test.ts +220 -88
  78. package/src/pi/failure-context.ts +161 -180
  79. package/src/pi/failure-path.test.ts +85 -88
  80. package/src/pi/file-commit.test.ts +78 -45
  81. package/src/pi/file-commit.ts +218 -151
  82. package/src/pi/file-read.test.ts +29 -0
  83. package/src/pi/file-read.ts +60 -0
  84. package/src/pi/file-snapshot.test.ts +1 -1
  85. package/src/pi/forget-tool.ts +189 -90
  86. package/src/pi/forget.test.ts +309 -22
  87. package/src/pi/forget.testing.ts +41 -113
  88. package/src/pi/fusion-card.test.ts +40 -14
  89. package/src/pi/fusion-card.ts +84 -50
  90. package/src/pi/grep-candidates.test.ts +127 -0
  91. package/src/pi/grep-candidates.ts +193 -0
  92. package/src/pi/grep-matrix.test.ts +83 -0
  93. package/src/pi/grep-output.ts +181 -138
  94. package/src/pi/grep-render.ts +28 -25
  95. package/src/pi/grep-scope.ts +61 -53
  96. package/src/pi/grep-search.ts +299 -242
  97. package/src/pi/grep-tool.ts +150 -140
  98. package/src/pi/grep-worker.mjs +4 -0
  99. package/src/pi/grep-worker.ts +14 -0
  100. package/src/pi/grep.test.ts +631 -632
  101. package/src/pi/model-budgets.test.ts +43 -0
  102. package/src/pi/model-budgets.ts +44 -0
  103. package/src/pi/mutation-outcome.testing.ts +5 -5
  104. package/src/pi/mutation-result.test.ts +21 -74
  105. package/src/pi/mutation-result.ts +74 -87
  106. package/src/pi/mutation-runner.ts +83 -75
  107. package/src/pi/output-budgets.test.ts +166 -0
  108. package/src/pi/path.ts +7 -0
  109. package/src/pi/read-tool.ts +151 -137
  110. package/src/pi/read.test.ts +39 -33
  111. package/src/pi/regex-worker-contract.ts +73 -0
  112. package/src/pi/regex-worker.ts +101 -0
  113. package/src/pi/registration.test.ts +111 -92
  114. package/src/pi/render.test.ts +193 -19
  115. package/src/pi/render.ts +137 -29
  116. package/src/pi/replace-regex.ts +11 -44
  117. package/src/pi/replace-tool.ts +38 -145
  118. package/src/pi/replace-worker-contract.ts +19 -0
  119. package/src/pi/replace-worker.ts +12 -8
  120. package/src/pi/replace.test.ts +93 -160
  121. package/src/pi/report-cause.ts +99 -0
  122. package/src/pi/report-failure.testing.ts +20 -0
  123. package/src/pi/report-schema.ts +512 -0
  124. package/src/pi/report.test.ts +276 -0
  125. package/src/pi/report.ts +288 -0
  126. package/src/pi/result-safety.test.ts +122 -427
  127. package/src/pi/rg-process.test.ts +78 -79
  128. package/src/pi/rg-process.ts +124 -177
  129. package/src/pi/rg-regex.test.ts +50 -0
  130. package/src/pi/rg-regex.ts +709 -0
  131. package/src/pi/text-stream.test.ts +67 -38
  132. package/src/pi/text-stream.ts +96 -75
  133. package/src/pi/tool-call.testing.ts +3 -39
  134. package/src/pi/write-tool.ts +45 -34
  135. package/src/pi/write.test.ts +45 -37
  136. package/src/testing/extension-loader.testing.ts +24 -0
  137. package/src/testing/installation.testing.ts +77 -0
  138. package/src/testing/process.testing.ts +33 -0
  139. package/src/testing/regex-host.testing.ts +20 -0
  140. package/src/testing/regex-translation-corpus.ts +308 -0
  141. package/src/testing/rg-line-listing.fixture.mjs +7 -0
  142. package/src/testing/run-tests.ts +47 -0
  143. package/src/testing/session.testing.ts +127 -0
  144. package/src/pi/rg-line-ranges.test.ts +0 -66
  145. package/src/pi/rg-line-ranges.ts +0 -75
  146. package/src/pi/rg-match-bytes.ts +0 -95
  147. package/src/pi/rg-text-view.ts +0 -192
  148. package/src/pi/tool-prompts.ts +0 -15
@@ -0,0 +1,89 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdtemp, rm, truncate, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { test } from "node:test";
6
+ import { formatSize } from "@earendil-works/pi-coding-agent";
7
+ import { DEFAULT_CONFIG } from "../pi/config.ts";
8
+ import { MAX_MULTILINE_SEARCH_BYTES } from "../pi/grep-search.ts";
9
+ import { MAX_UNNARROWED_SCAN_BYTES } from "../pi/grep-candidates.ts";
10
+ import { makeGrepOverrideWithBackend } from "../pi/grep-tool.ts";
11
+ import { OUTCOME_NEXT } from "../pi/report-schema.ts";
12
+ import { reportOf } from "../pi/report.ts";
13
+ import { callTool } from "../pi/tool-call.testing.ts";
14
+
15
+ test("all-file candidates exceed the scan budget → stop listing and retain scan facts with or without matches", async (t) => {
16
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-scan-budget-"));
17
+ t.after(() => rm(directory, { recursive: true, force: true }));
18
+ const scanLimitNext = OUTCOME_NEXT.find(([fact]) => fact === "scanLimit")?.[1];
19
+ assert.ok(scanLimitNext);
20
+ const padding: string[] = [];
21
+ // NUL files consume real scan bytes without building large regex inputs or exceeding the per-file cap.
22
+ for (let remaining = MAX_UNNARROWED_SCAN_BYTES; remaining > 0; ) {
23
+ const size = Math.min(remaining, MAX_MULTILINE_SEARCH_BYTES);
24
+ const path = join(directory, `padding-${padding.length}.bin`);
25
+ await writeFile(path, "");
26
+ await truncate(path, size);
27
+ padding.push(path);
28
+ remaining -= size;
29
+ }
30
+ const fixture = join(directory, "fixture.txt");
31
+ const blocked = join(directory, "beyond-budget.txt");
32
+ const unlisted = join(directory, "unlisted.txt");
33
+ await writeFile(blocked, "abc\n");
34
+ await writeFile(unlisted, "abc\n");
35
+ const paths = [fixture, ...padding, blocked, unlisted];
36
+ for (const scenario of [
37
+ { name: "matches", source: "abc\n", matches: 1, stderr: "" },
38
+ { name: "zero matches", source: "xxx\n", matches: 0, stderr: "" },
39
+ {
40
+ name: "zero matches with listing diagnostics",
41
+ source: "xxx\n",
42
+ matches: 0,
43
+ stderr: "listing interrupted",
44
+ },
45
+ ]) {
46
+ await t.test(scenario.name, async () => {
47
+ await writeFile(fixture, scenario.source);
48
+ const offered: string[] = [];
49
+ let stopped = false;
50
+ const tool = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {
51
+ runRgLines: async () => assert.fail("multiline candidates must use file listing"),
52
+ runRgPaths: async (_rgPath, _args, _signal, onFile) => {
53
+ for (const path of paths) {
54
+ offered.push(path);
55
+ if (!(await onFile(path))) {
56
+ stopped = true;
57
+ break;
58
+ }
59
+ }
60
+ return { code: scenario.stderr ? 2 : 0, stderr: scenario.stderr, stopped };
61
+ },
62
+ });
63
+ const result = await callTool(tool, {
64
+ path: directory,
65
+ pattern: "[^x\\s]{3}\\s",
66
+ literal: false,
67
+ multiline: true,
68
+ });
69
+ assert.equal(stopped, true);
70
+ assert.deepEqual(offered, [fixture, ...padding, blocked]);
71
+ const report = reportOf(result);
72
+ assert.ok(report);
73
+ assert.equal(report.candidates, "all");
74
+ assert.equal(report.scanLimit, formatSize(MAX_UNNARROWED_SCAN_BYTES));
75
+ if (scenario.stderr) {
76
+ assert.equal(result.isError, true);
77
+ assert.equal(report.error, "SEARCH_INCOMPLETE");
78
+ assert.match(report.diagnostics ?? "", /listing interrupted/);
79
+ } else {
80
+ assert.equal(result.isError, undefined);
81
+ assert.equal(report.matches, scenario.matches);
82
+ assert.equal(report.diagnostics, undefined);
83
+ assert.equal(result.details.incomplete, true);
84
+ assert.equal(report.next, scanLimitNext);
85
+ if (scenario.matches) assert.match(result.content[0].text, /fixture\.txt/);
86
+ }
87
+ });
88
+ }
89
+ });
@@ -0,0 +1,206 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join, resolve } from "node:path";
5
+ import { test } from "node:test";
6
+ import { rgPath } from "@vscode/ripgrep";
7
+ import { searchText, type GrepQuery } from "../core/search.ts";
8
+ import { searchFiles, type GrepFileMatch } from "../pi/grep-search.ts";
9
+ import { runRgLines, runRgPaths } from "../pi/rg-process.ts";
10
+ import { runCandidatePaths } from "../pi/grep-candidates.ts";
11
+ import { lineCandidatePatterns } from "../pi/rg-regex.ts";
12
+ import { extractPrefilter } from "../core/search-analysis.ts";
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.flags}`,
30
+ { skip: unsupportedByHost([example.pattern], example.flags) },
31
+ async () => {
32
+ const query: GrepQuery = {
33
+ patterns: [example.pattern],
34
+ flags: example.flags,
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 warnings: string[] = [];
75
+ const result = await searchFiles({
76
+ backend: {
77
+ runRgPaths: async () => assert.fail("unexpected file fallback"),
78
+ runRgLines: (rg, args, signal, maxLines, onFile) =>
79
+ runRgLines(rg, args, signal, maxLines, (path, lines) => {
80
+ candidates.set(resolve(path), lines);
81
+ return onFile(path, lines);
82
+ }),
83
+ },
84
+ rgPath,
85
+ scope: {
86
+ globs: [],
87
+ noIgnore: false,
88
+ follow: false,
89
+ searchPaths: inputs.map((input) => input.filePath),
90
+ },
91
+ query,
92
+ limit: 1000,
93
+ timeoutMs,
94
+ signal: AbortSignal.timeout(timeoutMs),
95
+ warnings,
96
+ });
97
+ const expected = inputs.map(({ bytes, filePath }) => {
98
+ const native = searchText({ source: bytes.toString("utf8"), query, limit: 1000 });
99
+ for (const row of native.lines)
100
+ assert.ok(
101
+ candidates.get(filePath)?.includes(row.lineNumber),
102
+ `missing candidate ${filePath}:${row.lineNumber}`,
103
+ );
104
+ if (example.rejectCandidates)
105
+ for (let offset = 0; offset < example.misses.length; offset++) {
106
+ const line = example.hits.length + offset + 1;
107
+ assert.equal(
108
+ candidates.get(filePath)?.includes(line) ?? false,
109
+ false,
110
+ `unfiltered ${JSON.stringify(example.misses[offset])}`,
111
+ );
112
+ }
113
+ return { filePath, rows: native.lines };
114
+ });
115
+ assert.deepEqual(warnings, []);
116
+ assert.deepEqual(sorted(result.files), sorted(expected));
117
+ },
118
+ );
119
+ }
120
+ });
121
+
122
+ test("real rg AND/OR file prefilter → excludes incomplete branches before JS verification", async (t) => {
123
+ const directory = await mkdtemp(join(tmpdir(), "hl-regex-conjunction-"));
124
+ t.after(() => rm(directory, { recursive: true, force: true }));
125
+ const fixtures = ["foo\nbar", "baz\nqux", "foo\nqux", "baz\nbar", "foo", "bar", "unrelated"];
126
+ const paths: string[] = [];
127
+ for (const [index, source] of fixtures.entries()) {
128
+ const path = join(directory, `${index}.txt`);
129
+ await writeFile(path, source);
130
+ paths.push(path);
131
+ }
132
+ const query: GrepQuery = {
133
+ patterns: ["(?:foo.*bar|baz.*qux)"],
134
+ flags: "s",
135
+ literal: false,
136
+ multiline: true,
137
+ };
138
+ const candidates: string[] = [];
139
+ const listing = await runCandidatePaths(
140
+ runRgPaths,
141
+ rgPath,
142
+ extractPrefilter(query),
143
+ ["--", directory],
144
+ AbortSignal.timeout(timeoutMs),
145
+ (path) => {
146
+ candidates.push(resolve(path));
147
+ return true;
148
+ },
149
+ );
150
+ assert.equal(listing.code, 0);
151
+ assert.equal(listing.stderr, "");
152
+ assert.deepEqual(candidates.sort(), paths.slice(0, 2).sort());
153
+ const warnings: string[] = [];
154
+ const result = await searchFiles({
155
+ backend: { runRgPaths, runRgLines },
156
+ rgPath,
157
+ scope: { globs: [], noIgnore: false, follow: false, searchPaths: [directory] },
158
+ query,
159
+ limit: 100,
160
+ timeoutMs,
161
+ warnings,
162
+ });
163
+ assert.deepEqual(warnings, []);
164
+ assert.deepEqual(
165
+ sorted(result.files),
166
+ sorted(
167
+ fixtures.map((source, index) => ({
168
+ filePath: paths[index],
169
+ rows: searchText({ source, query, limit: 100 }).lines,
170
+ })),
171
+ ),
172
+ );
173
+ });
174
+
175
+ test("oversized line translation → file prefilter fallback preserves JS results", async (t) => {
176
+ const directory = await mkdtemp(join(tmpdir(), "hl-regex-budget-"));
177
+ t.after(() => rm(directory, { recursive: true, force: true }));
178
+ const pattern = "a".repeat(30_000);
179
+ const query: GrepQuery = { patterns: [pattern], flags: "", literal: true, multiline: false };
180
+ assert.equal(lineCandidatePatterns(query), undefined);
181
+ const path = join(directory, "long.txt");
182
+ await writeFile(path, pattern);
183
+ let filePasses = 0;
184
+ const warnings: string[] = [];
185
+ const result = await searchFiles({
186
+ backend: {
187
+ runRgPaths: (...args) => {
188
+ filePasses++;
189
+ return runRgPaths(...args);
190
+ },
191
+ runRgLines: async () => assert.fail("translation budget must select file prefilter"),
192
+ },
193
+ rgPath,
194
+ scope: { globs: [], noIgnore: false, follow: false, searchPaths: [path] },
195
+ query,
196
+ limit: 10,
197
+ timeoutMs,
198
+ warnings,
199
+ });
200
+ assert.ok(filePasses > 0);
201
+ assert.deepEqual(warnings, []);
202
+ assert.deepEqual(
203
+ sorted(result.files),
204
+ sorted([{ filePath: path, rows: searchText({ source: pattern, query, limit: 10 }).lines }]),
205
+ );
206
+ });
@@ -1,9 +1,11 @@
1
1
  import { test } from "node:test";
2
2
  import assert from "node:assert/strict";
3
- import { mkdtemp, open, rm, writeFile } from "node:fs/promises";
3
+ import { mkdtemp, open, readFile, rm, writeFile } from "node:fs/promises";
4
4
  import { tmpdir } from "node:os";
5
5
  import { join } from "node:path";
6
6
  import { makeReadOverride } from "../pi/read-tool.ts";
7
+ import { makeEditOverride } from "../pi/edit-tool.ts";
8
+ import { byteRevision } from "../pi/file-commit.ts";
7
9
  import { makeGrepOverrideWithBackend } from "../pi/grep-tool.ts";
8
10
  import { computeLineHash } from "../core/hash.ts";
9
11
  import { callTool } from "../pi/tool-call.testing.ts";
@@ -36,6 +38,15 @@ test("read and line-based grep retain anchors on LF and CRLF files over 100 MiB"
36
38
  const result: any = await call(grep, { path, pattern: "needle", literal: true });
37
39
  assert.ok(result.content[0].text.includes(`1#${computeLineHash(1, "needle", 4)}│needle`));
38
40
  assert.doesNotMatch(result.content[0].text, /Search incomplete/);
41
+ const tail: Awaited<ReturnType<typeof grep.execute>> = await callTool(grep, {
42
+ path,
43
+ pattern: "(?<=ta)il",
44
+ literal: false,
45
+ });
46
+ assert.equal(tail.isError, undefined);
47
+ const body = tail.content[0];
48
+ assert.ok(body.type === "text");
49
+ assert.ok(body.text.includes(`103426#${computeLineHash(103426, "tail", 4)}│tail`));
39
50
  }
40
51
  } finally {
41
52
  await rm(directory, { recursive: true, force: true });
@@ -59,3 +70,48 @@ test("CRLF snapshots normalize terminators split across read chunks and preserve
59
70
  await rm(directory, { recursive: true, force: true });
60
71
  }
61
72
  });
73
+
74
+ test("copy/move a 150,000-line block → publish every captured line", async (t) => {
75
+ const directory = await mkdtemp(join(tmpdir(), "hashline-large-transfer-"));
76
+ t.after(() => rm(directory, { recursive: true, force: true }));
77
+ const path = join(directory, "transfer.txt");
78
+ const lineCount = 150_000;
79
+ const block = " value🙂\r\n".repeat(lineCount);
80
+ const source = `\uFEFFSTART\n${block}END`;
81
+ const read = makeReadOverride(directory, DEFAULT_CONFIG);
82
+ const edit = makeEditOverride(directory, DEFAULT_CONFIG);
83
+ const observedAnchor = async (line: number) => {
84
+ const result: Awaited<ReturnType<typeof read.execute>> = await callTool(read, {
85
+ path,
86
+ offset: line,
87
+ limit: 1,
88
+ });
89
+ const rows = result.content
90
+ .filter((part) => part.type === "text")
91
+ .map((part) => part.text)
92
+ .join("\n");
93
+ const match = new RegExp(`^(${line}#[0-9A-Z]+)│`, "m").exec(rows);
94
+ assert(match);
95
+ return match[1];
96
+ };
97
+ for (const op of ["copy", "move"] as const) {
98
+ await writeFile(path, source);
99
+ const [anchor, end, after] = await Promise.all([
100
+ observedAnchor(2),
101
+ observedAnchor(lineCount + 1),
102
+ observedAnchor(lineCount + 2),
103
+ ]);
104
+ const result: Awaited<ReturnType<typeof edit.execute>> = await callTool(edit, {
105
+ path,
106
+ edits: [{ op, anchor, end, after }],
107
+ });
108
+ const expected = Buffer.from(
109
+ (op === "copy" ? source : "\uFEFFSTART\nEND") + "\r\n" + block.slice(0, -2),
110
+ "utf8",
111
+ );
112
+ assert.deepEqual(await readFile(path), expected);
113
+ assert.ok("publishedRevision" in result.details);
114
+ assert.equal(result.details.publishedRevision, byteRevision(expected));
115
+ assert.equal(result.details.publication, "PUBLISHED");
116
+ }
117
+ });
@@ -0,0 +1,128 @@
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 { decodeReport, reportOf, type Report } from "../pi/report.ts";
9
+ import { openTestSession } from "../testing/session.testing.ts";
10
+
11
+ // Budget invalidation relies on Pi publishing the new model before tool preparation.
12
+ test("model selection → exposes the new limit and invalidates only on a selection change", async (t) => {
13
+ const observations: { source: string; id: string | undefined; limit: number | undefined }[] = [];
14
+ const fixture = await openTestSession(t, {
15
+ tools: [],
16
+ configure(pi) {
17
+ pi.on("session_start", (_event, ctx) => {
18
+ observations.push({ source: "start", id: ctx.model?.id, limit: ctx.model?.contextWindow });
19
+ });
20
+ pi.on("model_select", (event, ctx) => {
21
+ assert.equal(ctx.model?.id, event.model.id);
22
+ assert.equal(ctx.model?.contextWindow, event.model.contextWindow);
23
+ observations.push({
24
+ source: event.source,
25
+ id: event.model.id,
26
+ limit: event.model.contextWindow,
27
+ });
28
+ });
29
+ },
30
+ });
31
+ assert.equal(observations.length, 1);
32
+ assert.equal(observations[0].limit, fixture.model.contextWindow);
33
+ const small = { ...fixture.model, id: "small", contextWindow: 65_536 };
34
+ const large = { ...fixture.model, id: "large", contextWindow: 1_048_576 };
35
+ fixture.session.modelRuntime.registerProvider(fixture.model.provider, {
36
+ api: "openai-completions",
37
+ baseUrl: "https://unused.invalid",
38
+ apiKey: "local-test-placeholder",
39
+ models: [small, large],
40
+ });
41
+ await fixture.session.setModel(small);
42
+ await fixture.session.setModel(small);
43
+ assert.deepEqual(observations.slice(1), [
44
+ { source: "set", id: "small", limit: small.contextWindow },
45
+ ]);
46
+ fixture.session.setScopedModels([{ model: small }, { model: large }]);
47
+ await fixture.session.cycleModel();
48
+ assert.deepEqual(observations.at(-1), {
49
+ source: "cycle",
50
+ id: "large",
51
+ limit: large.contextWindow,
52
+ });
53
+ const ctx = fixture.session.extensionRunner.createToolContext("budget-probe", undefined);
54
+ assert.equal(ctx.model?.contextWindow, large.contextWindow);
55
+ await fixture.session.setModel(small);
56
+ assert.equal(ctx.model?.contextWindow, small.contextWindow);
57
+ });
58
+
59
+ test("model capacity changes → read and grep grow and shrink without re-registering tools", async (t) => {
60
+ const { session, cwd, model } = await openTestSession(t, {
61
+ tools: ["read", "grep"],
62
+ configure: (pi) => hashlineEdit(pi),
63
+ });
64
+ const path = join(cwd, "large-row.txt");
65
+ const text = "中文🙂".repeat(30_000);
66
+ await writeFile(path, text);
67
+ const tool = session.getToolDefinition("read");
68
+ assert.ok(tool);
69
+ const ctx = session.extensionRunner.createToolContext("read-budget", undefined);
70
+ await session.setModel({ ...model, id: "small", contextWindow: 65_536 });
71
+ const small = await callTool(tool, { path }, { ctx });
72
+ assert.ok(small.details.report.lineTooLong);
73
+ await session.setModel({ ...model, id: "large", contextWindow: 1_048_576 });
74
+ const large = await callTool(tool, { path }, { ctx });
75
+ assert.equal(large.details.report.lineTooLong, undefined);
76
+ assert.ok(large.content[0].text.includes(text));
77
+ await session.setModel({ ...model, id: "small", contextWindow: 65_536 });
78
+ const smallAgain = await callTool(tool, { path }, { ctx });
79
+ assert.deepEqual(smallAgain.details.report.lineTooLong, small.details.report.lineTooLong);
80
+ const grep = session.getToolDefinition("grep");
81
+ assert.ok(grep);
82
+ const smallSearch = await callTool(grep, { path, pattern: "中文", literal: true }, { ctx });
83
+ await session.setModel({ ...model, id: "large", contextWindow: 1_048_576 });
84
+ const largeSearch = await callTool(grep, { path, pattern: "中文", literal: true }, { ctx });
85
+ assert.equal(reportOf(smallSearch)?.linePreviewLimit, outputBudgetsFor(65_536).grepPreviewUnits);
86
+ assert.equal(
87
+ reportOf(largeSearch)?.linePreviewLimit,
88
+ outputBudgetsFor(1_048_576).grepPreviewUnits,
89
+ );
90
+ assert.ok(largeSearch.content[0].text.length > smallSearch.content[0].text.length);
91
+ assert.ok(!largeSearch.content[0].text.includes("\uFFFD"));
92
+ });
93
+
94
+ test("model switches before argument preparation → rejection uses the new budget without execution", async (t) => {
95
+ const { session, model } = await openTestSession(t, {
96
+ tools: ["edit"],
97
+ configure: (pi) => hashlineEdit(pi),
98
+ });
99
+ const tool = session.getToolDefinition("edit");
100
+ const prepare = tool?.prepareArguments;
101
+ assert.ok(prepare);
102
+ const args = {
103
+ path: "never-opened.txt",
104
+ edits: Array.from({ length: 400 }, () => ({ op: "append", body: [] })),
105
+ };
106
+ const reports: Report[] = [];
107
+ for (const [id, contextWindow] of [
108
+ ["small", 65_536],
109
+ ["large", 1_048_576],
110
+ ] as const) {
111
+ await session.setModel({ ...model, id, contextWindow });
112
+ assert.throws(
113
+ () => prepare(args),
114
+ (error: unknown) => {
115
+ assert.ok(error instanceof Error);
116
+ const budget = outputBudgetsFor(contextWindow);
117
+ assert.ok(Buffer.byteLength(error.message) <= budget.blockBytes);
118
+ const report = decodeReport(error.message);
119
+ assert.ok(report?.issues);
120
+ assert.equal(report.issues.length + (report.omittedIssues ?? 0), args.edits.length);
121
+ reports.push(report);
122
+ return true;
123
+ },
124
+ );
125
+ }
126
+ assert.ok(reports[0].omittedIssues);
127
+ assert.equal(reports[1].omittedIssues, undefined);
128
+ });
@@ -5,6 +5,8 @@ import { tmpdir } from "node:os";
5
5
  import { join } from "node:path";
6
6
  import { test } from "node:test";
7
7
  import { promisify } from "node:util";
8
+ import { fileURLToPath } from "node:url";
9
+ import { testEnvironment } from "../testing/process.testing.ts";
8
10
 
9
11
  const execFile = promisify(execFileCallback);
10
12
 
@@ -16,29 +18,14 @@ test("FIFO mutation targets → reject without waiting for a writer, including t
16
18
  const fifo = join(directory, "pipe");
17
19
  await execFile("mkfifo", [fifo]);
18
20
  await symlink("pipe", join(directory, "alias"));
19
- const moduleUrl = (path: string) => JSON.stringify(new URL(path, import.meta.url).href);
20
- // Isolate a blocking open so a regression cannot leave the test runner's I/O threads stuck.
21
- const script = `
22
- import assert from "node:assert/strict";
23
- import { join } from "node:path";
24
- import { makeEditOverride } from ${moduleUrl("../pi/edit-tool.ts")};
25
- import { makeReplaceTool } from ${moduleUrl("../pi/replace-tool.ts")};
26
- import { DEFAULT_CONFIG } from ${moduleUrl("../pi/config.ts")};
27
- import { callTool } from ${moduleUrl("../pi/tool-call.testing.ts")};
28
- const directory = process.argv[1];
29
- const cases = [
30
- [makeEditOverride(directory, DEFAULT_CONFIG), { edits: [{ op: "append", body: ["after"] }] }],
31
- [makeReplaceTool(directory, DEFAULT_CONFIG), { replacements: [{ find: "before", replace: "after" }] }],
32
- ];
33
- for (const path of ["pipe", "alias"]) {
34
- for (const [tool, args] of cases) {
35
- await assert.rejects(callTool(tool, { path: join(directory, path), ...args }),
36
- error => /not a regular file/.test(error.message) && error.publication === "NOT_PUBLISHED");
37
- }
38
- }
39
- `;
40
- await execFile(process.execPath, ["--input-type=module", "--eval", script, directory], {
41
- timeout: 10_000,
42
- killSignal: "SIGKILL",
43
- });
21
+ // Isolate a blocking open so a regression cannot leave the parent runner stuck.
22
+ await execFile(
23
+ process.execPath,
24
+ [fileURLToPath(new URL("./mutation-file-types.testing.ts", import.meta.url)), directory],
25
+ {
26
+ env: testEnvironment(directory),
27
+ timeout: 10_000,
28
+ killSignal: "SIGKILL",
29
+ },
30
+ );
44
31
  });
@@ -0,0 +1,33 @@
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/edit-tool.ts";
5
+ import { makeReplaceTool } from "../pi/replace-tool.ts";
6
+ import { DEFAULT_CONFIG } from "../pi/config.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: { edits: [{ op: "append", body: ["after"] }] },
16
+ },
17
+ {
18
+ tool: makeReplaceTool(directory, DEFAULT_CONFIG),
19
+ args: { replacements: [{ 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
+ }
@@ -0,0 +1,17 @@
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
+ test("npm archive without devDependencies → registered tools complete a real Pi workflow", async (t) => {
9
+ const installation = await installedExtension(t, "packed");
10
+ await access(join(installation.packageDir, "THIRD_PARTY_NOTICES.md"));
11
+ await runTestProcess(
12
+ process.execPath,
13
+ [fileURLToPath(new URL("./npm-package.testing.ts", import.meta.url)), installation.entry],
14
+ installation.root,
15
+ installation.agentDir,
16
+ );
17
+ });