@criogaid/pi-hashline-edit 0.6.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/README.md +78 -369
  2. package/README.zh-CN.md +162 -0
  3. package/THIRD_PARTY_NOTICES.md +80 -0
  4. package/package.json +11 -6
  5. package/src/core/AGENTS.md +20 -0
  6. package/src/core/apply.test.ts +328 -161
  7. package/src/core/apply.ts +129 -95
  8. package/src/core/case-fold.test.ts +44 -0
  9. package/src/core/case-fold.ts +77 -0
  10. package/src/core/character-set.test.ts +103 -0
  11. package/src/core/character-set.ts +184 -0
  12. package/src/core/errors.test.ts +23 -0
  13. package/src/core/errors.ts +70 -4
  14. package/src/core/hash.test.ts +1 -25
  15. package/src/core/hash.ts +0 -5
  16. package/src/core/lines.ts +32 -7
  17. package/src/core/ranges.test.ts +41 -9
  18. package/src/core/ranges.ts +11 -4
  19. package/src/core/regex.ts +51 -0
  20. package/src/core/replace-schema.ts +41 -0
  21. package/src/core/replace.test.ts +90 -0
  22. package/src/core/replace.ts +40 -56
  23. package/src/core/search-analysis.test.ts +208 -0
  24. package/src/core/search-analysis.ts +379 -0
  25. package/src/core/search-matrix.test.ts +64 -0
  26. package/src/core/search-matrix.testing.ts +183 -0
  27. package/src/core/search-schema.ts +18 -0
  28. package/src/core/search.test.ts +145 -0
  29. package/src/core/search.ts +119 -0
  30. package/src/core/text.test.ts +16 -8
  31. package/src/core/text.ts +26 -6
  32. package/src/core/types.ts +20 -17
  33. package/src/index.ts +24 -16
  34. package/src/integration/config-registration.test.ts +42 -28
  35. package/src/integration/fusion-dispatch.test.ts +62 -127
  36. package/src/integration/grep-errors.test.ts +50 -0
  37. package/src/integration/grep-flags.test.ts +273 -0
  38. package/src/integration/grep-js-completeness.test.ts +218 -0
  39. package/src/integration/grep-line-candidates.test.ts +233 -0
  40. package/src/integration/grep-matrix.test.ts +121 -0
  41. package/src/integration/grep-order.test.ts +78 -0
  42. package/src/integration/grep-path-matrix.test.ts +133 -0
  43. package/src/integration/grep-prefilter-coverage.test.ts +189 -0
  44. package/src/integration/grep-regex.test.ts +407 -0
  45. package/src/integration/grep-rg.test.ts +294 -436
  46. package/src/integration/grep-scan-budget.test.ts +111 -0
  47. package/src/integration/grep-translation.test.ts +206 -0
  48. package/src/integration/large-text.test.ts +56 -1
  49. package/src/integration/model-budget-lifecycle.test.ts +137 -0
  50. package/src/integration/mutation-file-types.test.ts +12 -26
  51. package/src/integration/mutation-file-types.testing.ts +33 -0
  52. package/src/integration/npm-package.test.ts +17 -0
  53. package/src/integration/npm-package.testing.ts +97 -0
  54. package/src/integration/publication-read-changes.test.ts +376 -0
  55. package/src/integration/read-changes.test.ts +98 -0
  56. package/src/integration/replace-package.test.ts +17 -36
  57. package/src/integration/replace-package.testing.ts +36 -0
  58. package/src/integration/replace-worker-boundary.test.ts +117 -0
  59. package/src/integration/report-replay.test.ts +90 -0
  60. package/src/integration/utf8-errors.test.ts +46 -0
  61. package/src/pi/AGENTS.md +54 -0
  62. package/src/pi/action-fusion.test.ts +256 -251
  63. package/src/pi/action-fusion.ts +121 -332
  64. package/src/pi/anchor-format.test.ts +16 -0
  65. package/src/pi/anchor-format.ts +16 -3
  66. package/src/pi/argument-diagnostics.ts +478 -0
  67. package/src/pi/argument-error.testing.ts +46 -0
  68. package/src/pi/argument-error.ts +76 -0
  69. package/src/pi/argument-format.test.ts +197 -0
  70. package/src/pi/argument-validation.test.ts +780 -49
  71. package/src/pi/argument-validation.ts +55 -58
  72. package/src/pi/budgets.ts +48 -21
  73. package/src/pi/codemode.test.ts +96 -0
  74. package/src/pi/config.test.ts +29 -15
  75. package/src/pi/config.ts +27 -13
  76. package/src/pi/diagnostic-buffer.test.ts +51 -16
  77. package/src/pi/diagnostic-buffer.ts +13 -16
  78. package/src/pi/directory-sync.test.ts +4 -1
  79. package/src/pi/edit-tool.ts +103 -99
  80. package/src/pi/error-text.ts +39 -16
  81. package/src/pi/execute.test.ts +407 -429
  82. package/src/pi/extension-loading.test.ts +7 -27
  83. package/src/pi/extension-loading.testing.ts +2 -14
  84. package/src/pi/failure-context.test.ts +265 -88
  85. package/src/pi/failure-context.ts +165 -181
  86. package/src/pi/failure-path.test.ts +179 -117
  87. package/src/pi/file-commit.test.ts +90 -73
  88. package/src/pi/file-commit.ts +216 -178
  89. package/src/pi/file-read.test.ts +29 -0
  90. package/src/pi/file-read.ts +60 -0
  91. package/src/pi/file-revision.ts +25 -0
  92. package/src/pi/file-snapshot.test.ts +1 -1
  93. package/src/pi/fusion-card-interaction.test.ts +143 -0
  94. package/src/pi/fusion-card.test.ts +233 -51
  95. package/src/pi/fusion-card.ts +246 -142
  96. package/src/pi/grep-candidates.test.ts +127 -0
  97. package/src/pi/grep-candidates.ts +191 -0
  98. package/src/pi/grep-matrix.test.ts +83 -0
  99. package/src/pi/grep-order.test.ts +323 -0
  100. package/src/pi/grep-output.testing.ts +24 -0
  101. package/src/pi/grep-output.ts +187 -151
  102. package/src/pi/grep-render.ts +31 -25
  103. package/src/pi/grep-scope.ts +62 -54
  104. package/src/pi/grep-search.ts +327 -241
  105. package/src/pi/grep-tool.ts +126 -147
  106. package/src/pi/grep-worker.mjs +4 -0
  107. package/src/pi/grep-worker.ts +14 -0
  108. package/src/pi/grep.test.ts +813 -713
  109. package/src/pi/model-budgets.test.ts +43 -0
  110. package/src/pi/model-budgets.ts +44 -0
  111. package/src/pi/mutation-outcome.testing.ts +6 -7
  112. package/src/pi/mutation-result.test.ts +45 -91
  113. package/src/pi/mutation-result.ts +86 -114
  114. package/src/pi/mutation-runner.ts +81 -81
  115. package/src/pi/output-budgets.test.ts +175 -0
  116. package/src/pi/path.ts +10 -1
  117. package/src/pi/pi.test.ts +4 -5
  118. package/src/pi/read-tool.ts +108 -142
  119. package/src/pi/read.test.ts +155 -96
  120. package/src/pi/regex-worker-contract.ts +55 -0
  121. package/src/pi/regex-worker.ts +95 -0
  122. package/src/pi/registration.test.ts +148 -124
  123. package/src/pi/render.test.ts +361 -84
  124. package/src/pi/render.ts +150 -32
  125. package/src/pi/replace-regex.ts +13 -48
  126. package/src/pi/replace-tool.ts +52 -158
  127. package/src/pi/replace-worker-contract.ts +10 -0
  128. package/src/pi/replace-worker.ts +12 -8
  129. package/src/pi/replace.test.ts +191 -340
  130. package/src/pi/report-cause.ts +103 -0
  131. package/src/pi/report-failure.testing.ts +20 -0
  132. package/src/pi/report-schema.ts +524 -0
  133. package/src/pi/report.test.ts +343 -0
  134. package/src/pi/report.ts +285 -0
  135. package/src/pi/result-safety.test.ts +216 -481
  136. package/src/pi/rg-process.test.ts +101 -76
  137. package/src/pi/rg-process.ts +130 -177
  138. package/src/pi/rg-regex.test.ts +67 -0
  139. package/src/pi/rg-regex.ts +715 -0
  140. package/src/pi/text-stream.test.ts +97 -69
  141. package/src/pi/text-stream.ts +97 -76
  142. package/src/pi/tool-call.testing.ts +20 -46
  143. package/src/pi/write-tool.ts +50 -41
  144. package/src/pi/write.test.ts +71 -95
  145. package/src/testing/extension-loader.testing.ts +24 -0
  146. package/src/testing/installation.testing.ts +77 -0
  147. package/src/testing/process.testing.ts +33 -0
  148. package/src/testing/regex-host.testing.ts +20 -0
  149. package/src/testing/regex-translation-corpus.ts +324 -0
  150. package/src/testing/rg-line-listing.fixture.mjs +7 -0
  151. package/src/testing/run-tests.ts +47 -0
  152. package/src/testing/session.testing.ts +127 -0
  153. package/src/integration/forget-grep.test.ts +0 -98
  154. package/src/pi/forget-tool.ts +0 -268
  155. package/src/pi/forget.test.ts +0 -343
  156. package/src/pi/forget.testing.ts +0 -273
  157. package/src/pi/rg-line-ranges.test.ts +0 -66
  158. package/src/pi/rg-line-ranges.ts +0 -75
  159. package/src/pi/rg-match-bytes.ts +0 -95
  160. package/src/pi/rg-text-view.ts +0 -192
  161. package/src/pi/tool-prompts.ts +0 -15
@@ -0,0 +1,324 @@
1
+ // Selected Test262 witnesses retain their upstream copyright and BSD license in THIRD_PARTY_NOTICES.md.
2
+ // Copyright 2022 Igalia S.L. All rights reserved.
3
+ // Copyright (C) 2017 the V8 project authors. All rights reserved.
4
+ // Copyright 2025 Mathias Bynens. All rights reserved.
5
+
6
+ export interface RegexWitness {
7
+ readonly pattern: string;
8
+ readonly flags: string;
9
+ readonly hits: readonly string[];
10
+ readonly misses: readonly string[];
11
+ readonly rejectCandidates: boolean;
12
+ readonly source: string;
13
+ }
14
+
15
+ const test262 = "https://github.com/tc39/test262/blob/main/test/built-ins/RegExp/";
16
+ const local = "JS-to-rg translation contract";
17
+
18
+ export const REGEX_TRANSLATION_CORPUS: readonly RegexWitness[] = [
19
+ {
20
+ pattern: "(?:([])\\1|b)",
21
+ flags: "",
22
+ hits: ["b"],
23
+ misses: ["a"],
24
+ rejectCandidates: true,
25
+ source: local,
26
+ },
27
+ {
28
+ pattern: "(?!a)[a-z]",
29
+ flags: "",
30
+ hits: ["b", "z"],
31
+ misses: ["a", "A"],
32
+ rejectCandidates: true,
33
+ source: local,
34
+ },
35
+ {
36
+ pattern: "(?=ab)a[bcd]",
37
+ flags: "",
38
+ hits: ["ab"],
39
+ misses: ["ac", "ad"],
40
+ rejectCandidates: true,
41
+ source: local,
42
+ },
43
+ {
44
+ pattern: "[a-z](?<=b)",
45
+ flags: "",
46
+ hits: ["b"],
47
+ misses: ["a", "c"],
48
+ rejectCandidates: true,
49
+ source: local,
50
+ },
51
+ {
52
+ pattern: "(?!ab)[a-z]{2}",
53
+ flags: "",
54
+ hits: ["ac", "ba"],
55
+ misses: ["ab"],
56
+ rejectCandidates: true,
57
+ source: local,
58
+ },
59
+ {
60
+ pattern: "[a-z]{2}(?<!ab)",
61
+ flags: "",
62
+ hits: ["ac", "ba"],
63
+ misses: ["ab"],
64
+ rejectCandidates: true,
65
+ source: local,
66
+ },
67
+ {
68
+ pattern: "(?i:(?!k)[a-z])",
69
+ flags: "u",
70
+ hits: ["a", "ſ"],
71
+ misses: ["k", "K", "K"],
72
+ rejectCandidates: true,
73
+ source: local,
74
+ },
75
+ {
76
+ pattern: "a\\b[ a]",
77
+ flags: "",
78
+ hits: ["a "],
79
+ misses: ["aa"],
80
+ rejectCandidates: true,
81
+ source: local,
82
+ },
83
+ {
84
+ pattern: "k\\b[\\w ]",
85
+ flags: "iu",
86
+ hits: ["k ", "K "],
87
+ misses: ["kk", "Kk"],
88
+ rejectCandidates: true,
89
+ source: local,
90
+ },
91
+ {
92
+ pattern: "(?m:[\\ra]^b)",
93
+ flags: "",
94
+ hits: ["\rb"],
95
+ misses: ["ab"],
96
+ rejectCandidates: true,
97
+ source: local,
98
+ },
99
+ {
100
+ pattern: "a^b",
101
+ flags: "",
102
+ hits: [],
103
+ misses: ["ab", "a^b"],
104
+ rejectCandidates: true,
105
+ source: local,
106
+ },
107
+ {
108
+ pattern: "(?=needle)",
109
+ flags: "",
110
+ hits: ["needle"],
111
+ misses: ["haystack"],
112
+ rejectCandidates: true,
113
+ source: local,
114
+ },
115
+ {
116
+ pattern: "(?<=needle)",
117
+ flags: "",
118
+ hits: ["needle"],
119
+ misses: ["haystack"],
120
+ rejectCandidates: true,
121
+ source: local,
122
+ },
123
+ {
124
+ pattern: "(?<=(a)\\1)",
125
+ flags: "",
126
+ hits: ["a", "ab"],
127
+ misses: ["b"],
128
+ rejectCandidates: true,
129
+ source: local,
130
+ },
131
+ {
132
+ pattern: "(?<=\\1(a))",
133
+ flags: "",
134
+ hits: ["aa"],
135
+ misses: ["a", "ab"],
136
+ rejectCandidates: true,
137
+ source: local,
138
+ },
139
+ {
140
+ pattern: "(cat|dog)\\1",
141
+ flags: "",
142
+ hits: ["catcat", "dogdog"],
143
+ misses: ["catdog", "dogcat"],
144
+ rejectCandidates: true,
145
+ source: local,
146
+ },
147
+ {
148
+ pattern: "(a|bc)\\1",
149
+ flags: "",
150
+ hits: ["aa", "bcbc"],
151
+ misses: ["abc", "bca"],
152
+ rejectCandidates: true,
153
+ source: local,
154
+ },
155
+ {
156
+ pattern: "(a{1,2})b\\1",
157
+ flags: "",
158
+ hits: ["aba", "aabaa"],
159
+ misses: ["abb"],
160
+ rejectCandidates: true,
161
+ source: local,
162
+ },
163
+ {
164
+ pattern: "(?i:([\\q{ks|ab}]))(?-i:\\1)",
165
+ flags: "v",
166
+ hits: ["KsKs", "abab"],
167
+ misses: ["Ksks", "abAB"],
168
+ rejectCandidates: true,
169
+ source: local,
170
+ },
171
+ {
172
+ pattern: "(a(?=b))b\\1",
173
+ flags: "",
174
+ hits: ["aba"],
175
+ misses: ["abb"],
176
+ rejectCandidates: false,
177
+ source: local,
178
+ },
179
+ {
180
+ pattern: "^(é|Σ|𐐀)$",
181
+ flags: "iu",
182
+ hits: ["É", "é", "ς", "σ", "Σ", "𐐨"],
183
+ misses: ["e", "s", "a"],
184
+ rejectCandidates: true,
185
+ source: local,
186
+ },
187
+ {
188
+ pattern: "^\\p{Letter}+$",
189
+ flags: "u",
190
+ hits: ["é", "Σ", "𐐀"],
191
+ misses: ["123", "😀"],
192
+ rejectCandidates: true,
193
+ source: local,
194
+ },
195
+ {
196
+ pattern: "^[\\p{Letter}--[a-z]]+$",
197
+ flags: "v",
198
+ hits: ["É", "Σ"],
199
+ misses: ["abc", "123"],
200
+ rejectCandidates: true,
201
+ source: local,
202
+ },
203
+ {
204
+ pattern: "^[^\\p{Letter}]$",
205
+ flags: "v",
206
+ hits: ["1", "😀"],
207
+ // Malformed-byte widening may also admit non-ASCII letters as candidates.
208
+ misses: ["a"],
209
+ rejectCandidates: true,
210
+ source: local,
211
+ },
212
+ {
213
+ pattern: `^[\\q{prefix${"a".repeat(300)}suffix|prefix${"b".repeat(300)}suffix}]$`,
214
+ flags: "v",
215
+ hits: [`prefix${"a".repeat(300)}suffix`, `prefix${"b".repeat(300)}suffix`],
216
+ misses: ["wrong", "prefixwrong", "wrongsuffix"],
217
+ rejectCandidates: true,
218
+ source: local,
219
+ },
220
+ {
221
+ pattern: "(?:(?<x>a)|(?<x>b))\\k<x>",
222
+ flags: "",
223
+ hits: ["aa", "bb"],
224
+ misses: ["abab", "cdef"],
225
+ rejectCandidates: false,
226
+ source: `${test262}named-groups/duplicate-names-exec.js`,
227
+ },
228
+ {
229
+ pattern: "(?:(?:(?<x>a)|(?<x>b))\\k<x>){2}",
230
+ flags: "",
231
+ hits: ["aabb"],
232
+ misses: ["abab"],
233
+ rejectCandidates: false,
234
+ source: `${test262}named-groups/duplicate-names-exec.js`,
235
+ },
236
+ {
237
+ pattern: "^(?:(?<a>x)|(?<a>y)|z)\\k<a>$",
238
+ flags: "",
239
+ hits: ["xx", "z"],
240
+ misses: ["zz"],
241
+ rejectCandidates: false,
242
+ source: `${test262}named-groups/duplicate-names-exec.js`,
243
+ },
244
+ {
245
+ pattern: "^(?:(?<a>x)|(?<a>y)|z){2}\\k<a>$",
246
+ flags: "",
247
+ hits: ["xz", "yz"],
248
+ misses: ["xzx", "yzy"],
249
+ rejectCandidates: false,
250
+ source: `${test262}named-groups/duplicate-names-exec.js`,
251
+ },
252
+ {
253
+ pattern: "(.)(?<=(\\1\\1))",
254
+ flags: "i",
255
+ hits: ["abB"],
256
+ misses: ["ab"],
257
+ rejectCandidates: false,
258
+ source: `${test262}lookBehind/back-references.js`,
259
+ },
260
+ {
261
+ pattern: "(..)(?<=\\1\\1\\1)",
262
+ flags: "",
263
+ hits: ["fababab"],
264
+ misses: ["fabxbab", "faxabab"],
265
+ rejectCandidates: false,
266
+ source: `${test262}lookBehind/back-references.js`,
267
+ },
268
+ {
269
+ pattern: "(?<=(.))(\\w+)(?=\\1)",
270
+ flags: "",
271
+ hits: [" 'foo' ", ' "foo" '],
272
+ misses: [' .foo" '],
273
+ rejectCandidates: false,
274
+ source: `${test262}lookBehind/back-references.js`,
275
+ },
276
+ {
277
+ pattern: "(?<=ab(?=c)\\wd)\\w\\w",
278
+ flags: "",
279
+ hits: ["abcdef"],
280
+ misses: [],
281
+ rejectCandidates: false,
282
+ source: `${test262}lookBehind/nested-lookaround.js`,
283
+ },
284
+ {
285
+ pattern: "(?<=a(?=([bc]{2}(?<!a{2}))d)\\w{3})\\w\\w",
286
+ flags: "",
287
+ hits: ["abcdef"],
288
+ misses: [],
289
+ rejectCandidates: false,
290
+ source: `${test262}lookBehind/nested-lookaround.js`,
291
+ },
292
+ {
293
+ pattern: "(?<=a(?=([bc]{2}(?<!a*))d)\\w{3})\\w\\w",
294
+ flags: "",
295
+ hits: [],
296
+ misses: ["abcdef"],
297
+ rejectCandidates: false,
298
+ source: `${test262}lookBehind/nested-lookaround.js`,
299
+ },
300
+ {
301
+ pattern: "(?<!(^|[ab]))\\w{2}",
302
+ flags: "",
303
+ hits: ["abcdef"],
304
+ misses: [],
305
+ rejectCandidates: false,
306
+ source: `${test262}lookBehind/captures-negative.js`,
307
+ },
308
+ {
309
+ pattern: "^[[0-9]--\\p{ASCII_Hex_Digit}]+$",
310
+ flags: "v",
311
+ hits: [],
312
+ misses: ["0", "9", "C", "☃", "𝌆", "🇧🇪"],
313
+ rejectCandidates: true,
314
+ source: `${test262}unicodeSets/generated/character-class-difference-character-property-escape.js`,
315
+ },
316
+ {
317
+ pattern: "^[[0-9]&&[0-9]]+$",
318
+ flags: "v",
319
+ hits: ["0", "9"],
320
+ misses: ["6\uFE0F\u20E3", "C", "☃", "𝌆", "🇧🇪"],
321
+ rejectCandidates: true,
322
+ source: `${test262}unicodeSets/generated/character-class-intersection-character-class.js`,
323
+ },
324
+ ];
@@ -0,0 +1,7 @@
1
+ // Emit protocol records for real-process smoke and termination checks.
2
+ const chunks = JSON.parse(process.argv[2]);
3
+ for (const chunk of chunks) {
4
+ await new Promise((resolve) => process.stdout.write(Buffer.from(chunk, "base64"), resolve));
5
+ await new Promise((resolve) => setImmediate(resolve));
6
+ }
7
+ if (process.argv[3] === "wait") setInterval(() => {}, 1000);
@@ -0,0 +1,47 @@
1
+ /** Keep npm's test entry points independent of personal Pi settings and Node loaders. */
2
+ import { spawnSync } from "node:child_process";
3
+ import { mkdtempSync, rmSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { testEnvironment } from "./process.testing.ts";
8
+
9
+ const unit = ["src/core/*.test.ts", "src/pi/*.test.ts"];
10
+ const integration = ["src/integration/*.test.ts"];
11
+ // Cartesian matrices take minutes per test; unit and integration skip them, `cartesian` runs only them.
12
+ const CARTESIAN = "^Cartesian ";
13
+ const suites = {
14
+ unit: { files: unit, filter: `--test-skip-pattern=${CARTESIAN}`, timeoutMs: 10 * 60 * 1000 },
15
+ integration: {
16
+ files: integration,
17
+ filter: `--test-skip-pattern=${CARTESIAN}`,
18
+ timeoutMs: 10 * 60 * 1000,
19
+ },
20
+ cartesian: {
21
+ files: [...unit, ...integration],
22
+ filter: `--test-name-pattern=${CARTESIAN}`,
23
+ timeoutMs: 60 * 60 * 1000,
24
+ },
25
+ };
26
+ const suite = process.argv[2];
27
+ if (suite !== "unit" && suite !== "integration" && suite !== "cartesian")
28
+ throw new Error("Expected unit, integration, or cartesian suite");
29
+ const { files, filter, timeoutMs } = suites[suite];
30
+ const agentDir = mkdtempSync(join(tmpdir(), "hashline-test-agent-"));
31
+ try {
32
+ const result = spawnSync(
33
+ process.execPath,
34
+ ["--test", filter, ...process.argv.slice(3), ...files],
35
+ {
36
+ cwd: fileURLToPath(new URL("../../", import.meta.url)),
37
+ env: testEnvironment(agentDir),
38
+ stdio: "inherit",
39
+ timeout: timeoutMs,
40
+ },
41
+ );
42
+ if (result.error) throw result.error;
43
+ if (result.signal) throw new Error(`Test suite stopped by ${result.signal}`);
44
+ process.exitCode = result.status ?? 1;
45
+ } finally {
46
+ rmSync(agentDir, { recursive: true, force: true });
47
+ }
@@ -0,0 +1,127 @@
1
+ /** Real Pi sessions with local model responses and no personal resources or provider traffic. */
2
+ import assert from "node:assert/strict";
3
+ import { mkdtemp, rm } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import type { TestContext } from "node:test";
7
+ import type { AssistantMessage } from "@earendil-works/pi-ai";
8
+ import { AssistantMessageEventStream } from "@earendil-works/pi-ai/utils/event-stream";
9
+ import {
10
+ createAgentSession,
11
+ DefaultResourceLoader,
12
+ type ExtensionAPI,
13
+ ModelRuntime,
14
+ SessionManager,
15
+ SettingsManager,
16
+ } from "@earendil-works/pi-coding-agent";
17
+
18
+ const TEST_PROVIDER = "hashline-test";
19
+ const TEST_CONTEXT_TOKENS = 100_000;
20
+ const TEST_OUTPUT_TOKENS = 1000;
21
+ export const SESSION_TIMEOUT_MS = 30_000;
22
+ export type TestResponse = Pick<AssistantMessage, "content" | "stopReason">;
23
+ type TestModel = NonNullable<ReturnType<ModelRuntime["getModel"]>>;
24
+
25
+ export function responseStream(model: TestModel, response: TestResponse) {
26
+ const message: AssistantMessage = {
27
+ role: "assistant",
28
+ ...response,
29
+ api: model.api,
30
+ provider: model.provider,
31
+ model: model.id,
32
+ timestamp: Date.now(),
33
+ usage: {
34
+ input: 0,
35
+ output: 0,
36
+ cacheRead: 0,
37
+ cacheWrite: 0,
38
+ totalTokens: 0,
39
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
40
+ },
41
+ };
42
+ const stream = new AssistantMessageEventStream();
43
+ stream.push({ type: "start", partial: message });
44
+ assert.ok(message.stopReason !== "pending");
45
+ if (message.stopReason === "error" || message.stopReason === "aborted") {
46
+ stream.push({ type: "error", reason: message.stopReason, error: message });
47
+ } else {
48
+ stream.push({ type: "done", reason: message.stopReason, message });
49
+ }
50
+ return stream;
51
+ }
52
+
53
+ export async function openTestSession(
54
+ t: TestContext,
55
+ options: {
56
+ readonly cwd?: string;
57
+ readonly tools: readonly string[];
58
+ readonly configure?: (pi: ExtensionAPI, cwd: string) => void | Promise<void>;
59
+ },
60
+ ) {
61
+ const cwd = options.cwd ?? (await mkdtemp(join(tmpdir(), "hashline-session-")));
62
+ let dispose: (() => void) | undefined;
63
+ t.after(async () => {
64
+ dispose?.();
65
+ if (options.cwd === undefined) await rm(cwd, { recursive: true, force: true });
66
+ });
67
+ const modelRuntime = await ModelRuntime.create({
68
+ authPath: join(cwd, "auth.json"),
69
+ modelsPath: null,
70
+ modelsStorePath: join(cwd, "models.json"),
71
+ refreshOnCreate: false,
72
+ allowModelNetwork: false,
73
+ });
74
+ modelRuntime.registerProvider(TEST_PROVIDER, {
75
+ api: "openai-completions",
76
+ baseUrl: "https://unused.invalid",
77
+ apiKey: "local-test-placeholder",
78
+ models: [
79
+ {
80
+ id: "test",
81
+ name: "Test",
82
+ input: ["text", "image"],
83
+ reasoning: false,
84
+ contextWindow: TEST_CONTEXT_TOKENS,
85
+ maxTokens: TEST_OUTPUT_TOKENS,
86
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
87
+ },
88
+ ],
89
+ });
90
+ const model = modelRuntime.getModel(TEST_PROVIDER, "test");
91
+ assert.ok(model);
92
+ const settingsManager = SettingsManager.inMemory({
93
+ compaction: { enabled: false },
94
+ retry: { enabled: false },
95
+ });
96
+ const configure = options.configure;
97
+ const loader = new DefaultResourceLoader({
98
+ cwd,
99
+ agentDir: cwd,
100
+ settingsManager,
101
+ noExtensions: true,
102
+ noSkills: true,
103
+ noPromptTemplates: true,
104
+ noThemes: true,
105
+ noContextFiles: true,
106
+ extensionFactories: configure ? [(pi) => configure(pi, cwd)] : [],
107
+ });
108
+ await loader.reload();
109
+ const sessionManager = SessionManager.inMemory(cwd);
110
+ const { session, extensionsResult } = await createAgentSession({
111
+ cwd,
112
+ agentDir: cwd,
113
+ modelRuntime,
114
+ model,
115
+ settingsManager,
116
+ resourceLoader: loader,
117
+ sessionManager,
118
+ tools: [...options.tools],
119
+ });
120
+ dispose = () => session.dispose();
121
+ assert.deepEqual(extensionsResult.errors, []);
122
+ session.agent.streamFunction = () => {
123
+ throw new Error("Install a scripted response before prompting");
124
+ };
125
+ await session.bindExtensions({});
126
+ return { cwd, session, model, sessionManager };
127
+ }
@@ -1,98 +0,0 @@
1
- /** Real ripgrep results consumed and forgotten through Pi's session lifecycle. */
2
- import assert from "node:assert/strict";
3
- import { writeFile } from "node:fs/promises";
4
- import { join } from "node:path";
5
- import { test } from "node:test";
6
- import { FORGET_MIN_BYTES } from "../pi/budgets.ts";
7
- import {
8
- assertForgotten,
9
- finish,
10
- forgetCall,
11
- openForgetSession,
12
- SESSION_TIMEOUT_MS,
13
- taggedResultId,
14
- toolResponse,
15
- toolResult,
16
- } from "../pi/forget.testing.ts";
17
-
18
- for (const encoding of ["UTF-8", "invalid UTF-8"] as const) {
19
- test(`real grep of ${encoding} logs then forget → matched content is absent from the next request`, {
20
- timeout: SESSION_TIMEOUT_MS,
21
- }, async (t) => {
22
- const f = await openForgetSession(t);
23
- const path = join(f.cwd, "search.log");
24
- const rowPayloadChars = 128;
25
- const rowCount = Math.ceil(FORGET_MIN_BYTES / rowPayloadChars);
26
- const rows = Array.from(
27
- { length: rowCount },
28
- (_, index) => `needle ${index} ${"x".repeat(rowPayloadChars)}`,
29
- );
30
- const bytes = Buffer.concat([
31
- Buffer.from(rows.join("\n")),
32
- encoding === "invalid UTF-8" ? Buffer.from([0xff]) : Buffer.alloc(0),
33
- Buffer.from("\n"),
34
- ]);
35
- await writeFile(path, bytes);
36
- await f.prompt(
37
- toolResponse({
38
- type: "toolCall",
39
- id: "search",
40
- name: "grep",
41
- arguments: { path, pattern: "needle", literal: true },
42
- }),
43
- (messages) => toolResponse(forgetCall(messages, "search")),
44
- finish,
45
- );
46
- const original = toolResult(f.requests[1], "search");
47
- assert.equal(original.isError, false);
48
- const text = original.content
49
- .filter((block) => block.type === "text")
50
- .map((block) => block.text)
51
- .join("\n");
52
- assert.ok(text.includes(rows[0]));
53
- if (encoding === "invalid UTF-8") assert.ok(text.includes("\uFFFD"));
54
- const id = taggedResultId(original);
55
- assert.ok(id);
56
- const forgotten = toolResult(f.requests[2], "search");
57
- assertForgotten(forgotten, id);
58
- const receipt = forgotten.content[0];
59
- assert.ok(receipt.type === "text" && !receipt.text.includes("needle"));
60
- assert.ok(receipt.type === "text" && !receipt.text.includes("search.log"));
61
- const displayReceipt = `grep /needle/ · ${rows.length} matches in 1 file`;
62
- assert.deepEqual(f.rawResult("forget-call").details, {
63
- forgotten: [{ id, receipt: displayReceipt }],
64
- });
65
- assert.ok(f.renderForgetCard().includes(displayReceipt));
66
- });
67
- }
68
-
69
- test("real grep reaches its limit across files → forget card reports the returned counts", {
70
- timeout: SESSION_TIMEOUT_MS,
71
- }, async (t) => {
72
- const f = await openForgetSession(t);
73
- const rowPayloadChars = 256;
74
- const rowsPerFile = Math.ceil(FORGET_MIN_BYTES / rowPayloadChars) + 1;
75
- const limit = rowsPerFile + 1;
76
- const paths = [join(f.cwd, "one.log"), join(f.cwd, "two.log")];
77
- const rows = Array.from(
78
- { length: rowsPerFile },
79
- (_, index) => `${index % 2 === 0 ? "needle" : "backup"} ${"x".repeat(rowPayloadChars)}`,
80
- );
81
- await Promise.all(paths.map((path) => writeFile(path, `${rows.join("\n")}\n`)));
82
- await f.prompt(
83
- toolResponse({
84
- type: "toolCall",
85
- id: "search",
86
- name: "grep",
87
- arguments: { path: paths, pattern: ["needle", "backup"], literal: true, limit },
88
- }),
89
- (messages) => toolResponse(forgetCall(messages, "search")),
90
- finish,
91
- );
92
- const id = taggedResultId(toolResult(f.requests[1], "search"));
93
- assert.ok(id);
94
- const receipt = `grep /needle | backup/ · ${limit} matches in ${paths.length} files · limit reached`;
95
- assert.deepEqual(f.rawResult("forget-call").details, { forgotten: [{ id, receipt }] });
96
- assert.ok(f.renderForgetCard().includes(receipt));
97
- assertForgotten(toolResult(f.requests[2], "search"), id);
98
- });