@criogaid/pi-hashline-edit 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/README.md +76 -220
  2. package/README.zh-CN.md +166 -0
  3. package/package.json +2 -1
  4. package/src/core/AGENTS.md +1 -1
  5. package/src/core/apply.test.ts +171 -133
  6. package/src/core/apply.ts +34 -31
  7. package/src/core/case-fold.test.ts +11 -7
  8. package/src/core/case-fold.ts +2 -6
  9. package/src/core/character-set.ts +14 -0
  10. package/src/core/hash.test.ts +1 -25
  11. package/src/core/hash.ts +0 -5
  12. package/src/core/lines.ts +25 -7
  13. package/src/core/ranges.test.ts +49 -9
  14. package/src/core/ranges.ts +15 -4
  15. package/src/core/regex.ts +36 -6
  16. package/src/core/replace-schema.ts +18 -11
  17. package/src/core/replace.test.ts +90 -0
  18. package/src/core/replace.ts +6 -5
  19. package/src/core/search-analysis.test.ts +9 -0
  20. package/src/core/search-analysis.ts +35 -31
  21. package/src/core/search.ts +1 -1
  22. package/src/core/types.ts +6 -8
  23. package/src/index.ts +2 -4
  24. package/src/integration/config-registration.test.ts +18 -10
  25. package/src/integration/fusion-dispatch.test.ts +41 -22
  26. package/src/integration/grep-flags.test.ts +6 -13
  27. package/src/integration/grep-js-completeness.test.ts +41 -31
  28. package/src/integration/grep-order.test.ts +78 -0
  29. package/src/integration/grep-path-matrix.test.ts +4 -3
  30. package/src/integration/grep-regex.test.ts +13 -16
  31. package/src/integration/grep-rg.test.ts +132 -92
  32. package/src/integration/grep-scan-budget.test.ts +27 -5
  33. package/src/integration/large-text.test.ts +4 -5
  34. package/src/integration/model-budget-lifecycle.test.ts +26 -8
  35. package/src/integration/mutation-file-types.test.ts +0 -1
  36. package/src/integration/mutation-file-types.testing.ts +2 -2
  37. package/src/integration/npm-package.testing.ts +7 -33
  38. package/src/integration/publication-read-changes.test.ts +60 -28
  39. package/src/integration/replace-package.testing.ts +4 -1
  40. package/src/integration/replace-worker-boundary.test.ts +34 -24
  41. package/src/integration/report-replay.test.ts +3 -3
  42. package/src/integration/utf8-errors.test.ts +3 -3
  43. package/src/pi/AGENTS.md +13 -14
  44. package/src/pi/action-fusion.test.ts +75 -220
  45. package/src/pi/action-fusion.ts +37 -74
  46. package/src/pi/anchor-format.test.ts +16 -0
  47. package/src/pi/anchor-format.ts +7 -3
  48. package/src/pi/argument-diagnostics.ts +35 -186
  49. package/src/pi/argument-error.testing.ts +7 -4
  50. package/src/pi/argument-error.ts +5 -7
  51. package/src/pi/argument-format.test.ts +25 -38
  52. package/src/pi/argument-validation.test.ts +446 -420
  53. package/src/pi/argument-validation.ts +4 -5
  54. package/src/pi/budgets.ts +5 -7
  55. package/src/pi/config.test.ts +15 -5
  56. package/src/pi/config.ts +6 -6
  57. package/src/pi/diagnostic-buffer.test.ts +2 -3
  58. package/src/pi/diagnostic-buffer.ts +2 -2
  59. package/src/pi/edit-tool.ts +175 -121
  60. package/src/pi/execute.test.ts +170 -227
  61. package/src/pi/failure-context.test.ts +61 -16
  62. package/src/pi/failure-context.ts +13 -10
  63. package/src/pi/failure-path.test.ts +115 -50
  64. package/src/pi/file-commit.test.ts +30 -46
  65. package/src/pi/file-commit.ts +11 -40
  66. package/src/pi/file-revision.ts +25 -0
  67. package/src/pi/fusion-card-interaction.test.ts +143 -0
  68. package/src/pi/fusion-card.test.ts +193 -37
  69. package/src/pi/fusion-card.ts +186 -116
  70. package/src/pi/grep-candidates.ts +25 -27
  71. package/src/pi/grep-matrix.test.ts +1 -1
  72. package/src/pi/grep-order.test.ts +323 -0
  73. package/src/pi/grep-output.testing.ts +24 -0
  74. package/src/pi/grep-output.ts +62 -69
  75. package/src/pi/grep-render.ts +4 -1
  76. package/src/pi/grep-scope.ts +1 -1
  77. package/src/pi/grep-search.ts +85 -56
  78. package/src/pi/grep-tool.ts +17 -48
  79. package/src/pi/grep.test.ts +271 -170
  80. package/src/pi/mutation-outcome.testing.ts +2 -3
  81. package/src/pi/mutation-result.test.ts +26 -19
  82. package/src/pi/mutation-result.ts +25 -40
  83. package/src/pi/mutation-runner.ts +9 -17
  84. package/src/pi/output-budgets.test.ts +27 -18
  85. package/src/pi/path.ts +3 -1
  86. package/src/pi/pi.test.ts +7 -6
  87. package/src/pi/read-tool.ts +32 -80
  88. package/src/pi/read.test.ts +145 -92
  89. package/src/pi/regex-worker-contract.ts +5 -23
  90. package/src/pi/regex-worker.ts +4 -10
  91. package/src/pi/registration.test.ts +106 -67
  92. package/src/pi/render.test.ts +239 -109
  93. package/src/pi/render.ts +42 -22
  94. package/src/pi/replace-regex.ts +3 -5
  95. package/src/pi/replace-tool.ts +29 -27
  96. package/src/pi/replace-worker-contract.ts +3 -12
  97. package/src/pi/replace.test.ts +144 -226
  98. package/src/pi/report-cause.ts +23 -19
  99. package/src/pi/report-failure.testing.ts +2 -2
  100. package/src/pi/report-schema.ts +60 -45
  101. package/src/pi/report.test.ts +138 -71
  102. package/src/pi/report.ts +40 -43
  103. package/src/pi/result-safety.test.ts +186 -131
  104. package/src/pi/rg-process.test.ts +36 -10
  105. package/src/pi/rg-process.ts +9 -3
  106. package/src/pi/rg-regex.test.ts +17 -0
  107. package/src/pi/rg-regex.ts +28 -22
  108. package/src/pi/text-stream.test.ts +35 -36
  109. package/src/pi/text-stream.ts +14 -14
  110. package/src/pi/tool-call.testing.ts +17 -7
  111. package/src/pi/write-tool.ts +9 -11
  112. package/src/pi/write.test.ts +43 -75
  113. package/src/testing/regex-translation-corpus.ts +16 -0
  114. package/src/testing/rg-line-listing.fixture.mjs +1 -1
  115. package/src/integration/forget-grep.test.ts +0 -148
  116. package/src/pi/forget-tool.ts +0 -367
  117. package/src/pi/forget.test.ts +0 -630
  118. package/src/pi/forget.testing.ts +0 -201
@@ -1,630 +0,0 @@
1
- import { rejectsArgument } from "./argument-error.testing.ts";
2
- import assert from "node:assert/strict";
3
- import { readFile, writeFile } from "node:fs/promises";
4
- import { join } from "node:path";
5
- import { test } from "node:test";
6
- import { DEFAULT_OUTPUT_BUDGETS, FORGET_MIN_BYTES } from "./budgets.ts";
7
- import { withResultTag } from "./forget-tool.ts";
8
- import { reportOf } from "./report.ts";
9
- import {
10
- assertForgotten,
11
- finish,
12
- forgetCall,
13
- openForgetSession,
14
- SESSION_TIMEOUT_MS,
15
- taggedResultId,
16
- toolResponse,
17
- toolResult,
18
- } from "./forget.testing.ts";
19
-
20
- const LOG_BODY = `build payload ${"x".repeat(FORGET_MIN_BYTES)}\nlast line\n`;
21
- const PNG = Buffer.from(
22
- "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=",
23
- "base64",
24
- );
25
- const NOT_FORGETTABLE_NEXT =
26
- "Do not call forget again for the notForgettable ids; those results stay in context.";
27
-
28
- for (const { name, filename, body, receiptSuffix } of [
29
- { name: "ordinary log", filename: "build.log", body: LOG_BODY, receiptSuffix: " · lines 1–2" },
30
- {
31
- name: "NUL log containing a row-like source line",
32
- filename: "build.log",
33
- body: `${LOG_BODY}\0\n1│source text\n`,
34
- receiptSuffix: "",
35
- },
36
- {
37
- name: "UTF-8 log containing a Unicode line separator",
38
- filename: "build.log",
39
- body: `before\u2028${LOG_BODY}`,
40
- receiptSuffix: " · lines 1–2",
41
- },
42
- { name: "PNG image", filename: "picture.png", body: PNG, receiptSuffix: " · image" },
43
- ]) {
44
- test(`${name} read then forgotten → the next request contains only a receipt`, {
45
- timeout: SESSION_TIMEOUT_MS,
46
- }, async (t) => {
47
- const f = await openForgetSession(t);
48
- await writeFile(join(f.cwd, filename), body);
49
- await f.prompt(
50
- toolResponse(f.read("read-log", filename)),
51
- (messages) => toolResponse(forgetCall(messages, "read-log")),
52
- finish,
53
- );
54
- const original = toolResult(f.requests[1], "read-log");
55
- const id = taggedResultId(original);
56
- assert.ok(id);
57
- if (typeof body === "string") {
58
- for (const line of body.trimEnd().split("\n")) {
59
- assert.ok(
60
- original.content.some((block) => block.type === "text" && block.text.includes(line)),
61
- );
62
- }
63
- } else {
64
- assert.ok(original.content.some((block) => block.type === "image"));
65
- }
66
- assert.equal(f.requests.length, 3, "A standalone forget must allow the model to continue");
67
- const forgotten = toolResult(f.requests[2], "read-log");
68
- const remainingText = forgotten.content
69
- .filter((block) => block.type === "text")
70
- .map((block) => block.text)
71
- .join("\n");
72
- assert.ok(
73
- !remainingText.includes("build payload"),
74
- "Consumed file content must not be sent again",
75
- );
76
- assert.ok(!remainingText.includes(filename), "File headers are forgotten with the body");
77
- assertForgotten(forgotten, id);
78
- const receipt = `${join(f.cwd, filename)}${receiptSuffix}`;
79
- assert.partialDeepStrictEqual(f.rawResult("forget-call").details, {
80
- forgotten: [{ id, receipt }],
81
- });
82
- assert.ok(f.renderForgetCard().includes(receipt));
83
- });
84
- }
85
-
86
- test("forget in a mixed tool batch → work continues and unselected results stay intact", {
87
- timeout: SESSION_TIMEOUT_MS,
88
- }, async (t) => {
89
- const f = await openForgetSession(t);
90
- for (const filename of ["build.log", "test.log", "keep.log"]) {
91
- await writeFile(join(f.cwd, filename), LOG_BODY);
92
- }
93
- await writeFile(join(f.cwd, "next.txt"), "next task");
94
- await f.prompt(
95
- toolResponse(
96
- f.read("selected"),
97
- f.read("selected-too", "test.log"),
98
- f.read("kept", "keep.log"),
99
- ),
100
- (messages) =>
101
- toolResponse(forgetCall(messages, "selected", "selected-too"), f.read("next", "next.txt")),
102
- finish,
103
- );
104
- assert.equal(f.requests.length, 3);
105
- for (const callId of ["selected", "selected-too"]) {
106
- const id = taggedResultId(toolResult(f.requests[1], callId));
107
- assert.ok(id);
108
- assertForgotten(toolResult(f.requests[2], callId), id);
109
- }
110
- assert.deepEqual(toolResult(f.requests[2], "kept"), toolResult(f.requests[1], "kept"));
111
- assert.equal(toolResult(f.requests[2], "next").isError, false);
112
- const expected = ["selected", "selected-too"].map((callId, index) => ({
113
- id: taggedResultId(toolResult(f.requests[1], callId)),
114
- receipt: `${join(f.cwd, index === 0 ? "build.log" : "test.log")} · lines 1–2`,
115
- }));
116
- assert.partialDeepStrictEqual(f.rawResult("forget-call").details, { forgotten: expected });
117
- const displayed = f.renderForgetCard();
118
- assert.equal(displayed.split("\n")[0].trimEnd(), `forget · ${expected.length} results`);
119
- assert.doesNotMatch(displayed, /Forgotten ·/);
120
- const expanded = f.renderForgetCard(true);
121
- for (const { id, receipt } of expected) {
122
- assert.ok(id);
123
- assert.ok(displayed.includes(receipt));
124
- assert.ok(!displayed.includes(id));
125
- assert.ok(expanded.includes(`${id} · ${receipt}`));
126
- }
127
- assert.ok(!displayed.includes("keep.log"));
128
- const payload = JSON.stringify(await f.requestPayload(2));
129
- assert.doesNotMatch(payload, /"forgetReceipt"|"forgotten":/);
130
- for (const { receipt } of expected) assert.ok(!payload.includes(receipt));
131
- const response = toolResult(f.requests[2], "forget-call");
132
- assert.deepEqual(response.content, f.rawResult("forget-call").content);
133
- for (const block of response.content) {
134
- if (block.type === "text") assert.ok(payload.includes(JSON.stringify(block.text).slice(1, -1)));
135
- }
136
- });
137
-
138
- for (const mode of ["pagination", "byte truncation"] as const) {
139
- test(`read stops at ${mode} → forget receipt names only the returned lines`, {
140
- timeout: SESSION_TIMEOUT_MS,
141
- }, async (t) => {
142
- const f = await openForgetSession(t);
143
- const path = join(f.cwd, "build.log");
144
- const maxReadBytes = DEFAULT_OUTPUT_BUDGETS.readBytes;
145
- const trailingLine = mode === "byte truncation" ? "y".repeat(maxReadBytes) : "next page";
146
- await writeFile(path, `skip this line\n${LOG_BODY}${trailingLine}\n`);
147
- const read = f.read("read-log");
148
- await f.prompt(
149
- toolResponse({
150
- ...read,
151
- arguments: { ...read.arguments, offset: 2, limit: mode === "pagination" ? 2 : 3 },
152
- }),
153
- (messages) => toolResponse(forgetCall(messages, "read-log")),
154
- finish,
155
- );
156
- const id = taggedResultId(toolResult(f.requests[1], "read-log"));
157
- assert.ok(id);
158
- const receipt = `${path} · lines 2–3${mode === "byte truncation" ? " · truncated" : ""}`;
159
- assert.partialDeepStrictEqual(f.rawResult("forget-call").details, {
160
- forgotten: [{ id, receipt }],
161
- });
162
- assert.ok(f.renderForgetCard().includes(receipt));
163
- assertForgotten(toolResult(f.requests[2], "read-log"), id);
164
- const details = f.rawResult("read-log").details;
165
- assert.ok(details && typeof details === "object");
166
- assert.ok(mode === "pagination" ? "pagination" in details : "truncation" in details);
167
- });
168
- }
169
-
170
- test("forget with a note → calls, saved facts, source bytes and raw session remain", {
171
- timeout: SESSION_TIMEOUT_MS,
172
- }, async (t) => {
173
- const f = await openForgetSession(t);
174
- const path = join(f.cwd, "build.log");
175
- const note = "Build failed during dependency installation.";
176
- const read = f.read("read-log");
177
- await writeFile(path, LOG_BODY);
178
- await f.prompt(
179
- toolResponse(read),
180
- (messages) => {
181
- const call = forgetCall(messages, "read-log");
182
- return toolResponse({ ...call, arguments: { ...call.arguments, note } });
183
- },
184
- finish,
185
- );
186
- const calls = f.requests[2].flatMap((message) =>
187
- message.role === "assistant"
188
- ? message.content.filter((block) => block.type === "toolCall")
189
- : [],
190
- );
191
- assert.deepEqual(
192
- calls.find((call) => call.id === read.id),
193
- read,
194
- );
195
- assert.equal(calls.find((call) => call.name === "forget")?.arguments.note, note);
196
- const original = f.sessionManager
197
- .getEntries()
198
- .find(
199
- (entry) =>
200
- entry.type === "message" &&
201
- entry.message.role === "toolResult" &&
202
- entry.message.toolCallId === read.id,
203
- );
204
- assert.ok(original?.type === "message" && original.message.role === "toolResult");
205
- assert.deepEqual(original.message.content, toolResult(f.requests[1], read.id).content);
206
- assert.equal(await readFile(path, "utf8"), LOG_BODY);
207
- });
208
-
209
- for (const invalid of ["old result", "unknown result"] as const) {
210
- test(`forget includes an eligible id and ${invalid} → only the eligible result is forgotten`, {
211
- timeout: SESSION_TIMEOUT_MS,
212
- }, async (t) => {
213
- const f = await openForgetSession(t);
214
- await writeFile(join(f.cwd, "build.log"), LOG_BODY);
215
- await writeFile(join(f.cwd, "next.txt"), "next task");
216
- await f.prompt(
217
- toolResponse(f.read("old")),
218
- toolResponse(f.read("current")),
219
- (messages) => {
220
- const current = forgetCall(messages, "current");
221
- const currentId = taggedResultId(toolResult(messages, "current"));
222
- const oldId = taggedResultId(toolResult(messages, "old"));
223
- assert.ok(currentId && oldId);
224
- const invalidId = invalid === "old result" ? oldId : "r00000";
225
- assert.notEqual(currentId, invalidId);
226
- assert.notEqual(oldId, "r00000");
227
- return toolResponse(
228
- { ...current, arguments: { ids: [currentId, invalidId] } },
229
- f.read("next", "next.txt"),
230
- );
231
- },
232
- finish,
233
- );
234
- const before = f.requests[2];
235
- const after = f.requests[3];
236
- const currentId = taggedResultId(toolResult(before, "current"));
237
- const oldId = taggedResultId(toolResult(before, "old"));
238
- assert.ok(currentId && oldId);
239
- const invalidId = invalid === "old result" ? oldId : "r00000";
240
- const result = toolResult(after, "forget-call");
241
- assert.equal(result.isError, false);
242
- assert.deepEqual(reportOf(result), {
243
- tool: "forget",
244
- forgotten: [currentId],
245
- notForgettable: [invalidId],
246
- next: NOT_FORGETTABLE_NEXT,
247
- });
248
- assertForgotten(toolResult(after, "current"), currentId);
249
- assert.deepEqual(toolResult(after, "old"), toolResult(before, "old"));
250
- assert.equal(toolResult(after, "next").isError, false);
251
- const receipt = `${join(f.cwd, "build.log")} · lines 1–2`;
252
- const displayed = f.renderForgetCard();
253
- assert.ok(displayed.includes(receipt));
254
- assert.ok(displayed.includes(`not forgettable: ${invalidId}`));
255
- assert.ok(displayed.indexOf(receipt) < displayed.indexOf("not forgettable:"));
256
- });
257
- }
258
-
259
- for (const reply of ["rejected forget", "successful mixed batch", "forget-only"] as const) {
260
- test(`${reply} reply after tagged results → later forget rejects every previous id`, {
261
- timeout: SESSION_TIMEOUT_MS,
262
- }, async (t) => {
263
- const f = await openForgetSession(t);
264
- await writeFile(join(f.cwd, "build.log"), LOG_BODY);
265
- await writeFile(join(f.cwd, "next.txt"), "next task");
266
- await f.prompt(
267
- toolResponse(f.read("batch-first"), f.read("batch-second")),
268
- (messages) => {
269
- const call = forgetCall(messages, "batch-first");
270
- for (const source of ["batch-first", "batch-second"])
271
- assert.notEqual(taggedResultId(toolResult(messages, source)), "r00000");
272
- const forget = {
273
- ...call,
274
- id: "forget-first-attempt",
275
- arguments: reply === "rejected forget" ? { ids: ["r00000"] } : call.arguments,
276
- };
277
- return toolResponse(
278
- forget,
279
- ...(reply === "successful mixed batch" ? [f.read("next", "next.txt")] : []),
280
- );
281
- },
282
- (messages) => {
283
- const original = toolResult(f.requests[1], "batch-first");
284
- const firstId = taggedResultId(original);
285
- assert.ok(firstId);
286
- const firstAttempt = toolResult(messages, "forget-first-attempt");
287
- if (reply === "rejected forget") {
288
- assert.equal(firstAttempt.isError, true);
289
- assert.deepEqual(reportOf(firstAttempt), {
290
- error: "NOT_FORGETTABLE",
291
- tool: "forget",
292
- message: "No id names a tagged result of the previous response.",
293
- notForgettable: ["r00000"],
294
- next: NOT_FORGETTABLE_NEXT,
295
- });
296
- assert.deepEqual(toolResult(messages, "batch-first"), original);
297
- } else {
298
- assert.equal(firstAttempt.isError, false);
299
- assert.deepEqual(reportOf(firstAttempt), { tool: "forget", forgotten: [firstId] });
300
- assertForgotten(toolResult(messages, "batch-first"), firstId);
301
- }
302
- assert.deepEqual(
303
- toolResult(messages, "batch-second"),
304
- toolResult(f.requests[1], "batch-second"),
305
- );
306
- return toolResponse({
307
- ...forgetCall(f.requests[1], "batch-first", "batch-second"),
308
- id: "forget-second-attempt",
309
- });
310
- },
311
- finish,
312
- );
313
- const ids = ["batch-first", "batch-second"].map((source) => {
314
- const id = taggedResultId(toolResult(f.requests[1], source));
315
- assert.ok(id);
316
- return id;
317
- });
318
- const after = f.requests[3];
319
- const secondAttempt = toolResult(after, "forget-second-attempt");
320
- assert.equal(secondAttempt.isError, true);
321
- assert.partialDeepStrictEqual(reportOf(secondAttempt), {
322
- error: "NOT_FORGETTABLE",
323
- notForgettable: ids,
324
- });
325
- for (const source of ["batch-first", "batch-second"])
326
- assert.deepEqual(toolResult(after, source), toolResult(f.requests[2], source));
327
- });
328
- }
329
-
330
- test("forget mixed with read → the next forget removes new results and reports old ids", {
331
- timeout: SESSION_TIMEOUT_MS,
332
- }, async (t) => {
333
- const f = await openForgetSession(t);
334
- await writeFile(join(f.cwd, "build.log"), LOG_BODY);
335
- await f.prompt(
336
- toolResponse(f.read("old-batch"), f.read("old-kept")),
337
- (messages) => toolResponse(forgetCall(messages, "old-batch"), f.read("new-batch")),
338
- (messages) => {
339
- const oldId = taggedResultId(toolResult(f.requests[1], "old-batch"));
340
- const keptId = taggedResultId(toolResult(messages, "old-kept"));
341
- const newId = taggedResultId(toolResult(messages, "new-batch"));
342
- assert.ok(oldId && keptId && newId);
343
- assert.equal(toolResult(messages, "forget-call").isError, false);
344
- assertForgotten(toolResult(messages, "old-batch"), oldId);
345
- return toolResponse({
346
- type: "toolCall",
347
- id: "forget-new-batch",
348
- name: "forget",
349
- arguments: { ids: [newId, oldId, keptId] },
350
- });
351
- },
352
- finish,
353
- );
354
- const oldId = taggedResultId(toolResult(f.requests[1], "old-batch"));
355
- const keptId = taggedResultId(toolResult(f.requests[1], "old-kept"));
356
- const newId = taggedResultId(toolResult(f.requests[2], "new-batch"));
357
- assert.ok(oldId && keptId && newId);
358
- const result = toolResult(f.requests[3], "forget-new-batch");
359
- assert.equal(result.isError, false);
360
- assert.partialDeepStrictEqual(reportOf(result), {
361
- forgotten: [newId],
362
- notForgettable: [oldId, keptId],
363
- });
364
- assertForgotten(toolResult(f.requests[3], "old-batch"), oldId);
365
- assertForgotten(toolResult(f.requests[3], "new-batch"), newId);
366
- assert.deepEqual(toolResult(f.requests[3], "old-kept"), toolResult(f.requests[1], "old-kept"));
367
- });
368
-
369
- test("forget after a reply without tools → the earlier batch is no longer forgettable", {
370
- timeout: SESSION_TIMEOUT_MS,
371
- }, async (t) => {
372
- const f = await openForgetSession(t);
373
- await writeFile(join(f.cwd, "build.log"), LOG_BODY);
374
- await f.prompt(toolResponse(f.read("earlier-batch")), finish);
375
- const original = toolResult(f.requests[1], "earlier-batch");
376
- const id = taggedResultId(original);
377
- assert.ok(id);
378
- await f.prompt(
379
- toolResponse({
380
- type: "toolCall",
381
- id: "forget-after-text",
382
- name: "forget",
383
- arguments: { ids: [id] },
384
- }),
385
- finish,
386
- );
387
- const after = f.requests.at(-1);
388
- assert.ok(after);
389
- const rejected = toolResult(after, "forget-after-text");
390
- assert.equal(rejected.isError, true);
391
- assert.partialDeepStrictEqual(reportOf(rejected), {
392
- error: "NOT_FORGETTABLE",
393
- notForgettable: [id],
394
- });
395
- assert.deepEqual(toolResult(after, "earlier-batch"), original);
396
- });
397
-
398
- for (const invalid of [
399
- "empty ids",
400
- "duplicate ids",
401
- "malformed id",
402
- "multiple invalid fields",
403
- ] as const) {
404
- test(`${invalid} from a model call → schema rejection leaves the result intact`, {
405
- timeout: SESSION_TIMEOUT_MS,
406
- }, async (t) => {
407
- const f = await openForgetSession(t);
408
- await writeFile(join(f.cwd, "build.log"), LOG_BODY);
409
- await f.prompt(
410
- toolResponse(f.read("read-log")),
411
- (messages) => {
412
- const id = taggedResultId(toolResult(messages, "read-log"));
413
- assert.ok(id);
414
- const ids =
415
- invalid === "empty ids"
416
- ? []
417
- : invalid === "duplicate ids"
418
- ? [id, id]
419
- : ["not-a-result-id"];
420
- return toolResponse({
421
- type: "toolCall",
422
- id: "forget-call",
423
- name: "forget",
424
- arguments: invalid === "multiple invalid fields" ? { ids, note: "" } : { ids },
425
- });
426
- },
427
- finish,
428
- );
429
- const rejection = toolResult(f.requests[2], "forget-call");
430
- assert.equal(rejection.isError, true);
431
- if (invalid === "multiple invalid fields") {
432
- const text = rejection.content
433
- .filter((block) => block.type === "text")
434
- .map((block) => block.text)
435
- .join("\n");
436
- rejectsArgument("ids[0]", /pattern/)(new Error(text));
437
- rejectsArgument("note")(new Error(text));
438
- }
439
- assert.deepEqual(toolResult(f.requests[2], "read-log"), toolResult(f.requests[1], "read-log"));
440
- });
441
- }
442
-
443
- function collidingToolCallIds() {
444
- const maxCandidateCalls = 20_000;
445
- const seen = new Map<string, string>();
446
- for (let index = 0; index < maxCandidateCalls; index++) {
447
- const callId = `call_collision_${index}`;
448
- const id = taggedResultId(
449
- withResultTag(
450
- callId,
451
- {
452
- report: { tool: "read", path: "build.log" },
453
- payload: [{ type: "text", text: LOG_BODY }],
454
- },
455
- true,
456
- () => "build.log",
457
- ),
458
- );
459
- assert.ok(id);
460
- const earlier = seen.get(id);
461
- if (earlier) return [earlier, callId];
462
- seen.set(id, callId);
463
- }
464
- throw new Error("No colliding public result tags found within the fixture search bound");
465
- }
466
-
467
- for (const batch of ["same batch", "older visible batch"] as const) {
468
- test(`distinct read calls have colliding tags in the ${batch} → neither result is forgotten`, {
469
- timeout: SESSION_TIMEOUT_MS,
470
- }, async (t) => {
471
- const f = await openForgetSession(t);
472
- await writeFile(join(f.cwd, "build.log"), LOG_BODY);
473
- // Find real call ids that collide, then let actual reads produce the tagged results.
474
- const [first, second] = collidingToolCallIds();
475
- const reads =
476
- batch === "same batch"
477
- ? [toolResponse(f.read(first), f.read(second))]
478
- : [toolResponse(f.read(first)), toolResponse(f.read(second))];
479
- await f.prompt(
480
- ...reads,
481
- (messages) => {
482
- assert.equal(
483
- taggedResultId(toolResult(messages, first)),
484
- taggedResultId(toolResult(messages, second)),
485
- );
486
- return toolResponse(forgetCall(messages, second));
487
- },
488
- finish,
489
- );
490
- const before = f.requests[reads.length];
491
- const after = f.requests[reads.length + 1];
492
- assert.equal(toolResult(after, "forget-call").isError, true);
493
- assert.deepEqual(toolResult(after, first), toolResult(before, first));
494
- assert.deepEqual(toolResult(after, second), toolResult(before, second));
495
- });
496
- }
497
-
498
- test("model output is truncated while requesting forget → Pi rejects the call and retains the result", {
499
- timeout: SESSION_TIMEOUT_MS,
500
- }, async (t) => {
501
- const f = await openForgetSession(t);
502
- await writeFile(join(f.cwd, "build.log"), LOG_BODY);
503
- await f.prompt(
504
- toolResponse(f.read("read-log")),
505
- (messages) => ({
506
- content: [forgetCall(messages, "read-log")],
507
- stopReason: "length",
508
- }),
509
- finish,
510
- );
511
- assert.equal(toolResult(f.requests[2], "forget-call").isError, true);
512
- assert.deepEqual(toolResult(f.requests[2], "read-log"), toolResult(f.requests[1], "read-log"));
513
- });
514
-
515
- for (const entry of ["direct", "codemode"] as const) {
516
- test(`codemode forwards mixed text outputs → ${entry} forget removes the whole script result`, {
517
- timeout: SESSION_TIMEOUT_MS,
518
- }, async (t) => {
519
- const f = await openForgetSession(t);
520
- await writeFile(join(f.cwd, "build.log"), LOG_BODY);
521
- await writeFile(join(f.cwd, "keep.log"), "keep this source\n");
522
- const code = [
523
- 'const results = await Promise.all([tools.read({path:"build.log"}), tools.read({path:"keep.log"})]);',
524
- "text({selected: results[0], another: results[1]});",
525
- 'text("Saved conclusion from the script.");',
526
- ].join("\n");
527
- const note = "Keep the saved conclusion.";
528
- await f.prompt(
529
- toolResponse({ type: "toolCall", id: "script-read", name: "codemode", arguments: { code } }),
530
- (messages) => {
531
- const result = toolResult(messages, "script-read");
532
- const id = taggedResultId(result);
533
- assert.ok(id, "The persisted codemode result must have a usable tag");
534
- const text = result.content
535
- .filter((block) => block.type === "text")
536
- .map((block) => block.text)
537
- .join("\n");
538
- assert.equal(
539
- [...text.matchAll(/\bresultId\b/g)].length,
540
- 1,
541
- "Nested reads must not expose unusable tags",
542
- );
543
- assert.match(text, /entire codemode output/i);
544
- const call = forgetCall(messages, "script-read");
545
- return toolResponse(
546
- entry === "direct"
547
- ? { ...call, arguments: { ...call.arguments, note } }
548
- : {
549
- type: "toolCall",
550
- id: "forget-script",
551
- name: "codemode",
552
- arguments: {
553
- code: `text(await tools.forget(${JSON.stringify({ ids: [id], note })}));`,
554
- },
555
- },
556
- );
557
- },
558
- finish,
559
- );
560
- const original = toolResult(f.requests[1], "script-read");
561
- const id = taggedResultId(original);
562
- assert.ok(id);
563
- assertForgotten(toolResult(f.requests[2], "script-read"), id);
564
- assert.deepEqual(f.rawResult("script-read").content, original.content);
565
- assert.equal(await readFile(join(f.cwd, "build.log"), "utf8"), LOG_BODY);
566
- assert.equal(await readFile(join(f.cwd, "keep.log"), "utf8"), "keep this source\n");
567
- assert.equal(
568
- toolResult(f.requests[2], entry === "direct" ? "forget-call" : "forget-script").isError,
569
- false,
570
- );
571
- const payload = JSON.stringify(await f.requestPayload(2));
572
- assert.ok(!payload.includes("build payload"));
573
- assert.ok(!payload.includes("keep this source"));
574
- assert.ok(payload.includes(note));
575
- });
576
- }
577
-
578
- for (const { name, code } of [
579
- {
580
- name: "filtered short read",
581
- code: 'await tools.read({path:"build.log"}); text("only a conclusion");',
582
- },
583
- {
584
- name: "script error",
585
- code: 'text(await tools.read({path:"build.log"})); throw new Error("script failed");',
586
- },
587
- { name: "no read calls", code: `text(${JSON.stringify(LOG_BODY)});` },
588
- ]) {
589
- test(`codemode ${name} → output has no forget tags`, {
590
- timeout: SESSION_TIMEOUT_MS,
591
- }, async (t) => {
592
- const f = await openForgetSession(t);
593
- await writeFile(join(f.cwd, "build.log"), LOG_BODY);
594
- await f.prompt(
595
- toolResponse({ type: "toolCall", id: "script-read", name: "codemode", arguments: { code } }),
596
- finish,
597
- );
598
- const output = toolResult(f.requests[1], "script-read")
599
- .content.filter((block) => block.type === "text")
600
- .map((block) => block.text)
601
- .join("\n");
602
- assert.doesNotMatch(output, /\[result r[0-9a-f]{5}\]/);
603
- });
604
- }
605
-
606
- test("codemode prints inspection text and an image → forget removes every output block", {
607
- timeout: SESSION_TIMEOUT_MS,
608
- }, async (t) => {
609
- const f = await openForgetSession(t);
610
- await writeFile(join(f.cwd, "build.log"), LOG_BODY);
611
- await f.prompt(
612
- toolResponse({
613
- type: "toolCall",
614
- id: "script-image",
615
- name: "codemode",
616
- arguments: {
617
- code: `text(await tools.read({path:"build.log"})); image(${JSON.stringify({ type: "image", data: PNG.toString("base64"), mimeType: "image/png" })});`,
618
- },
619
- }),
620
- (messages) => toolResponse(forgetCall(messages, "script-image")),
621
- finish,
622
- );
623
- const original = toolResult(f.requests[1], "script-image");
624
- assert.ok(original.content.some((block) => block.type === "image"));
625
- const id = taggedResultId(original);
626
- assert.ok(id);
627
- assertForgotten(toolResult(f.requests[2], "script-image"), id);
628
- assert.deepEqual(f.rawResult("script-image").content, original.content);
629
- assert.equal(await readFile(join(f.cwd, "build.log"), "utf8"), LOG_BODY);
630
- });