@criogaid/pi-hashline-edit 0.6.1 → 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 +55 -57
  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 +7 -27
  76. package/src/pi/extension-loading.testing.ts +2 -14
  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
@@ -1,10 +1,11 @@
1
+ import { rejectsArgument } from "./argument-error.testing.ts";
1
2
  import assert from "node:assert/strict";
2
3
  import { readFile, writeFile } from "node:fs/promises";
3
4
  import { join } from "node:path";
4
5
  import { test } from "node:test";
5
- import { FORGET_MIN_BYTES } from "./budgets.ts";
6
+ import { DEFAULT_OUTPUT_BUDGETS, FORGET_MIN_BYTES } from "./budgets.ts";
6
7
  import { withResultTag } from "./forget-tool.ts";
7
- import { DEFAULT_CONFIG } from "./config.ts";
8
+ import { reportOf } from "./report.ts";
8
9
  import {
9
10
  assertForgotten,
10
11
  finish,
@@ -21,6 +22,8 @@ const PNG = Buffer.from(
21
22
  "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=",
22
23
  "base64",
23
24
  );
25
+ const NOT_FORGETTABLE_NEXT =
26
+ "Do not call forget again for the notForgettable ids; those results stay in context.";
24
27
 
25
28
  for (const { name, filename, body, receiptSuffix } of [
26
29
  { name: "ordinary log", filename: "build.log", body: LOG_BODY, receiptSuffix: " · lines 1–2" },
@@ -73,7 +76,9 @@ for (const { name, filename, body, receiptSuffix } of [
73
76
  assert.ok(!remainingText.includes(filename), "File headers are forgotten with the body");
74
77
  assertForgotten(forgotten, id);
75
78
  const receipt = `${join(f.cwd, filename)}${receiptSuffix}`;
76
- assert.deepEqual(f.rawResult("forget-call").details, { forgotten: [{ id, receipt }] });
79
+ assert.partialDeepStrictEqual(f.rawResult("forget-call").details, {
80
+ forgotten: [{ id, receipt }],
81
+ });
77
82
  assert.ok(f.renderForgetCard().includes(receipt));
78
83
  });
79
84
  }
@@ -108,7 +113,7 @@ test("forget in a mixed tool batch → work continues and unselected results sta
108
113
  id: taggedResultId(toolResult(f.requests[1], callId)),
109
114
  receipt: `${join(f.cwd, index === 0 ? "build.log" : "test.log")} · lines 1–2`,
110
115
  }));
111
- assert.deepEqual(f.rawResult("forget-call").details, { forgotten: expected });
116
+ assert.partialDeepStrictEqual(f.rawResult("forget-call").details, { forgotten: expected });
112
117
  const displayed = f.renderForgetCard();
113
118
  assert.equal(displayed.split("\n")[0].trimEnd(), `forget · ${expected.length} results`);
114
119
  assert.doesNotMatch(displayed, /Forgotten ·/);
@@ -126,7 +131,7 @@ test("forget in a mixed tool batch → work continues and unselected results sta
126
131
  const response = toolResult(f.requests[2], "forget-call");
127
132
  assert.deepEqual(response.content, f.rawResult("forget-call").content);
128
133
  for (const block of response.content) {
129
- if (block.type === "text") assert.ok(payload.includes(block.text));
134
+ if (block.type === "text") assert.ok(payload.includes(JSON.stringify(block.text).slice(1, -1)));
130
135
  }
131
136
  });
132
137
 
@@ -136,7 +141,7 @@ for (const mode of ["pagination", "byte truncation"] as const) {
136
141
  }, async (t) => {
137
142
  const f = await openForgetSession(t);
138
143
  const path = join(f.cwd, "build.log");
139
- const maxReadBytes = DEFAULT_CONFIG.read.maxKiB * 1024;
144
+ const maxReadBytes = DEFAULT_OUTPUT_BUDGETS.readBytes;
140
145
  const trailingLine = mode === "byte truncation" ? "y".repeat(maxReadBytes) : "next page";
141
146
  await writeFile(path, `skip this line\n${LOG_BODY}${trailingLine}\n`);
142
147
  const read = f.read("read-log");
@@ -151,7 +156,9 @@ for (const mode of ["pagination", "byte truncation"] as const) {
151
156
  const id = taggedResultId(toolResult(f.requests[1], "read-log"));
152
157
  assert.ok(id);
153
158
  const receipt = `${path} · lines 2–3${mode === "byte truncation" ? " · truncated" : ""}`;
154
- assert.deepEqual(f.rawResult("forget-call").details, { forgotten: [{ id, receipt }] });
159
+ assert.partialDeepStrictEqual(f.rawResult("forget-call").details, {
160
+ forgotten: [{ id, receipt }],
161
+ });
155
162
  assert.ok(f.renderForgetCard().includes(receipt));
156
163
  assertForgotten(toolResult(f.requests[2], "read-log"), id);
157
164
  const details = f.rawResult("read-log").details;
@@ -200,34 +207,194 @@ test("forget with a note → calls, saved facts, source bytes and raw session re
200
207
  });
201
208
 
202
209
  for (const invalid of ["old result", "unknown result"] as const) {
203
- test(`eligible id combined with ${invalid} → the whole forget call is rejected`, {
210
+ test(`forget includes an eligible id and ${invalid} → only the eligible result is forgotten`, {
204
211
  timeout: SESSION_TIMEOUT_MS,
205
212
  }, async (t) => {
206
213
  const f = await openForgetSession(t);
207
214
  await writeFile(join(f.cwd, "build.log"), LOG_BODY);
215
+ await writeFile(join(f.cwd, "next.txt"), "next task");
208
216
  await f.prompt(
209
217
  toolResponse(f.read("old")),
210
218
  toolResponse(f.read("current")),
211
219
  (messages) => {
212
220
  const current = forgetCall(messages, "current");
213
221
  const currentId = taggedResultId(toolResult(messages, "current"));
214
- assert.ok(currentId);
215
- const old = taggedResultId(toolResult(messages, "old"));
216
- assert.ok(old);
217
- const invalidId = invalid === "old result" ? old : "r00000";
218
- assert.notEqual(taggedResultId(toolResult(messages, "current")), invalidId);
219
- return toolResponse({ ...current, arguments: { ids: [currentId, invalidId] } });
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
+ );
220
231
  },
221
232
  finish,
222
233
  );
223
- assert.equal(toolResult(f.requests[3], "forget-call").isError, true);
224
- for (const id of ["old", "current"]) {
225
- assert.deepEqual(toolResult(f.requests[3], id), toolResult(f.requests[2], id));
226
- }
227
- assert.ok(!f.sessionManager.getEntries().some((entry) => entry.type === "context_edit"));
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:"));
228
256
  });
229
257
  }
230
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
+
231
398
  for (const invalid of [
232
399
  "empty ids",
233
400
  "duplicate ids",
@@ -266,8 +433,8 @@ for (const invalid of [
266
433
  .filter((block) => block.type === "text")
267
434
  .map((block) => block.text)
268
435
  .join("\n");
269
- assert.match(text, /\n - ids/);
270
- assert.match(text, /\n - note:/);
436
+ rejectsArgument("ids[0]", /pattern/)(new Error(text));
437
+ rejectsArgument("note")(new Error(text));
271
438
  }
272
439
  assert.deepEqual(toolResult(f.requests[2], "read-log"), toolResult(f.requests[1], "read-log"));
273
440
  });
@@ -281,7 +448,10 @@ function collidingToolCallIds() {
281
448
  const id = taggedResultId(
282
449
  withResultTag(
283
450
  callId,
284
- { content: [{ type: "text", text: LOG_BODY }] },
451
+ {
452
+ report: { tool: "read", path: "build.log" },
453
+ payload: [{ type: "text", text: LOG_BODY }],
454
+ },
285
455
  true,
286
456
  () => "build.log",
287
457
  ),
@@ -341,3 +511,120 @@ test("model output is truncated while requesting forget → Pi rejects the call
341
511
  assert.equal(toolResult(f.requests[2], "forget-call").isError, true);
342
512
  assert.deepEqual(toolResult(f.requests[2], "read-log"), toolResult(f.requests[1], "read-log"));
343
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
+ });
@@ -1,31 +1,25 @@
1
1
  /** Real Pi sessions with scripted model responses; no provider requests leave the process. */
2
2
  import assert from "node:assert/strict";
3
- import { mkdtemp, rm } from "node:fs/promises";
4
- import { tmpdir } from "node:os";
5
3
  import { join } from "node:path";
6
4
  import { stripVTControlCharacters } from "node:util";
7
5
  import type { TestContext } from "node:test";
8
6
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
9
- import type { AssistantMessage, Message, ToolCall } from "@earendil-works/pi-ai";
10
- import { AssistantMessageEventStream } from "@earendil-works/pi-ai/utils/event-stream";
7
+ import type { Message, ToolCall } from "@earendil-works/pi-ai";
11
8
  import { normalizeContext } from "@earendil-works/pi-ai/utils/transcript";
12
9
  import { stream as streamCompletions } from "@earendil-works/pi-ai/api/openai-completions";
13
- import {
14
- createAgentSession,
15
- initTheme,
16
- DefaultResourceLoader,
17
- ModelRuntime,
18
- SessionManager,
19
- SettingsManager,
20
- } from "@earendil-works/pi-coding-agent";
10
+ import { initTheme } from "@earendil-works/pi-coding-agent";
11
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
12
+ import { decodeReport, reportOf } from "./report.ts";
13
+ import { openTestSession, responseStream, type TestResponse } from "../testing/session.testing.ts";
21
14
  import { DEFAULT_CONFIG } from "./config.ts";
22
15
  import { registerForgetTool } from "./forget-tool.ts";
23
16
  import { makeGrepOverride } from "./grep-tool.ts";
24
17
  import { makeReadOverride } from "./read-tool.ts";
25
18
  import { theme } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/theme/theme.js";
19
+ import { createCodemodeToolDefinition } from "../../node_modules/@earendil-works/pi-coding-agent/dist/extensions/codemode/tool.js";
26
20
 
27
- export const SESSION_TIMEOUT_MS = 30_000;
28
- type Response = Pick<AssistantMessage, "content" | "stopReason">;
21
+ export { SESSION_TIMEOUT_MS } from "../testing/session.testing.ts";
22
+ type Response = TestResponse;
29
23
  type Script = Response | ((messages: readonly Message[]) => Response);
30
24
  export const finish: Response = {
31
25
  content: [{ type: "text", text: "Processed." }],
@@ -36,10 +30,21 @@ export const toolResponse = (...content: ToolCall[]): Response => ({
36
30
  stopReason: "toolUse",
37
31
  });
38
32
 
39
- /** Extract the public result tag without assuming how its id is generated. */
40
- export function taggedResultId(result: Pick<AgentToolResult<unknown>, "content">) {
41
- const last = result.content.at(-1);
42
- return last?.type === "text" ? /^\[result (r[0-9a-f]{5})\]$/.exec(last.text)?.[1] : undefined;
33
+ /** Extract a public id from JSON inspection reports, excluding forgotten receipts. */
34
+ export function taggedResultId(
35
+ result: Pick<AgentToolResult<unknown>, "content"> & {
36
+ readonly toolName?: string;
37
+ readonly details?: unknown;
38
+ },
39
+ ) {
40
+ const toolName = result.toolName ?? reportOf(result)?.tool;
41
+ const ids = result.content.flatMap((block) => {
42
+ if (block.type !== "text") return [];
43
+ const report = decodeReport(block.text, toolName);
44
+ const id = report?.contentForgotten ? undefined : report?.resultId;
45
+ return id ? [id] : [];
46
+ });
47
+ return ids.length === 1 ? ids[0] : undefined;
43
48
  }
44
49
 
45
50
  export function toolResult(messages: readonly Message[], id: string) {
@@ -61,74 +66,21 @@ export function forgetCall(messages: readonly Message[], ...sourceIds: string[])
61
66
  return { type: "toolCall", id: "forget-call", name: "forget", arguments: { ids } };
62
67
  }
63
68
 
64
- export async function openForgetSession(t: TestContext) {
65
- const cwd = await mkdtemp(join(tmpdir(), "hashline-forget-"));
66
- let disposeSession: (() => void) | undefined;
67
- t.after(async () => {
68
- disposeSession?.();
69
- await rm(cwd, { recursive: true, force: true });
70
- });
71
- const modelRuntime = await ModelRuntime.create({
72
- authPath: join(cwd, "auth.json"),
73
- modelsPath: null,
74
- modelsStorePath: join(cwd, "models.json"),
75
- refreshOnCreate: false,
76
- allowModelNetwork: false,
77
- });
78
- modelRuntime.registerProvider("forget-test", {
79
- api: "openai-completions",
80
- baseUrl: "https://unused.invalid",
81
- apiKey: "local-test-placeholder",
82
- models: [
83
- {
84
- id: "test",
85
- name: "Test",
86
- input: ["text", "image"],
87
- reasoning: false,
88
- contextWindow: 100_000,
89
- maxTokens: 1000,
90
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
91
- },
92
- ],
93
- });
94
- const model = modelRuntime.getModel("forget-test", "test");
95
- assert.ok(model);
96
- const sessionManager = SessionManager.inMemory(cwd);
97
- const settingsManager = SettingsManager.inMemory({
98
- compaction: { enabled: false },
99
- retry: { enabled: false },
100
- });
101
- const loader = new DefaultResourceLoader({
102
- cwd,
103
- agentDir: cwd,
104
- settingsManager,
105
- noExtensions: true,
106
- noSkills: true,
107
- noPromptTemplates: true,
108
- noThemes: true,
109
- noContextFiles: true,
110
- extensionFactories: [
111
- (pi) => {
112
- const config = { ...DEFAULT_CONFIG, forget: true };
113
- pi.registerTool(makeReadOverride(cwd, config));
114
- pi.registerTool(makeGrepOverride(cwd, config));
115
- registerForgetTool(pi);
116
- },
117
- ],
118
- });
119
- await loader.reload();
120
- const { session, extensionsResult } = await createAgentSession({
121
- cwd,
122
- agentDir: cwd,
123
- modelRuntime,
124
- model,
125
- settingsManager,
126
- resourceLoader: loader,
127
- sessionManager,
128
- tools: ["read", "grep", "forget"],
69
+ export async function openForgetSession(
70
+ t: TestContext,
71
+ configure?: (pi: ExtensionAPI, cwd: string) => void,
72
+ ) {
73
+ const { cwd, session, model, sessionManager } = await openTestSession(t, {
74
+ tools: ["read", "grep", "forget", "codemode"],
75
+ configure(pi, cwd) {
76
+ const config = { ...DEFAULT_CONFIG, forget: true };
77
+ pi.registerTool(makeReadOverride(cwd, config));
78
+ pi.registerTool(makeGrepOverride(cwd, config));
79
+ registerForgetTool(pi);
80
+ pi.registerTool(createCodemodeToolDefinition());
81
+ configure?.(pi, cwd);
82
+ },
129
83
  });
130
- disposeSession = () => session.dispose();
131
- assert.deepEqual(extensionsResult.errors, []);
132
84
  const requests: Message[][] = [];
133
85
  const scripts: Script[] = [];
134
86
  session.agent.streamFunction = (_model, context) => {
@@ -136,33 +88,8 @@ export async function openForgetSession(t: TestContext) {
136
88
  const script = scripts.shift();
137
89
  assert.ok(script, "Unexpected model request after the scripted responses");
138
90
  const response = typeof script === "function" ? script(context.messages) : script;
139
- const message: AssistantMessage = {
140
- role: "assistant",
141
- ...response,
142
- api: model.api,
143
- provider: model.provider,
144
- model: model.id,
145
- timestamp: Date.now(),
146
- usage: {
147
- input: 0,
148
- output: 0,
149
- cacheRead: 0,
150
- cacheWrite: 0,
151
- totalTokens: 0,
152
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
153
- },
154
- };
155
- const stream = new AssistantMessageEventStream();
156
- stream.push({ type: "start", partial: message });
157
- assert.ok(message.stopReason !== "pending");
158
- if (message.stopReason === "error" || message.stopReason === "aborted") {
159
- stream.push({ type: "error", reason: message.stopReason, error: message });
160
- } else {
161
- stream.push({ type: "done", reason: message.stopReason, message });
162
- }
163
- return stream;
91
+ return responseStream(model, response);
164
92
  };
165
- await session.bindExtensions({});
166
93
  const rawResult = (id: string) => {
167
94
  const entry = sessionManager
168
95
  .getEntries()
@@ -267,7 +194,8 @@ export function assertForgotten(result: ReturnType<typeof toolResult>, id: strin
267
194
  assert.equal(result.content.length, 1);
268
195
  const receipt = result.content[0];
269
196
  assert.equal(receipt.type, "text");
270
- assert.ok(receipt.type === "text" && receipt.text.includes(id));
271
- assert.ok(receipt.type === "text" && receipt.text.includes("forgotten"));
197
+ const report = receipt.type === "text" ? decodeReport(receipt.text, result.toolName) : undefined;
198
+ assert.equal(report?.resultId, id);
199
+ assert.equal(report?.contentForgotten, true);
272
200
  assert.equal(taggedResultId(result), undefined);
273
201
  }