@criogaid/pi-hashline-edit 0.5.0 → 0.6.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 (66) hide show
  1. package/README.md +66 -22
  2. package/package.json +6 -6
  3. package/src/core/apply.test.ts +66 -16
  4. package/src/core/apply.ts +36 -19
  5. package/src/core/lines.ts +3 -3
  6. package/src/core/text.test.ts +30 -1
  7. package/src/core/text.ts +8 -3
  8. package/src/index.ts +2 -0
  9. package/src/integration/forget-grep.test.ts +98 -0
  10. package/src/integration/fusion-dispatch.test.ts +343 -0
  11. package/src/integration/grep-rg.test.ts +466 -111
  12. package/src/integration/large-text.test.ts +3 -5
  13. package/src/integration/mutation-file-types.test.ts +44 -0
  14. package/src/pi/action-fusion.test.ts +158 -79
  15. package/src/pi/action-fusion.ts +105 -34
  16. package/src/pi/anchor-format.test.ts +46 -0
  17. package/src/pi/anchor-format.ts +21 -2
  18. package/src/pi/argument-validation.test.ts +136 -0
  19. package/src/pi/argument-validation.ts +103 -0
  20. package/src/pi/budgets.ts +4 -1
  21. package/src/pi/config.test.ts +1 -0
  22. package/src/pi/config.ts +4 -0
  23. package/src/pi/diagnostic-buffer.test.ts +58 -0
  24. package/src/pi/diagnostic-buffer.ts +59 -0
  25. package/src/pi/directory-sync.test.ts +1 -1
  26. package/src/pi/edit-tool.ts +56 -37
  27. package/src/pi/execute.test.ts +185 -645
  28. package/src/pi/failure-context.test.ts +4 -3
  29. package/src/pi/failure-path.test.ts +3 -3
  30. package/src/pi/file-commit.test.ts +24 -17
  31. package/src/pi/file-commit.ts +36 -9
  32. package/src/pi/file-snapshot.test.ts +24 -0
  33. package/src/pi/forget-tool.ts +268 -0
  34. package/src/pi/forget.test.ts +343 -0
  35. package/src/pi/forget.testing.ts +273 -0
  36. package/src/pi/fusion-card.test.ts +26 -0
  37. package/src/pi/fusion-card.ts +21 -6
  38. package/src/pi/grep-output.ts +82 -55
  39. package/src/pi/grep-render.ts +8 -11
  40. package/src/pi/grep-scope.ts +6 -31
  41. package/src/pi/grep-search.ts +94 -58
  42. package/src/pi/grep-tool.ts +50 -59
  43. package/src/pi/grep.test.ts +412 -208
  44. package/src/pi/mutation-result.test.ts +23 -0
  45. package/src/pi/mutation-runner.ts +8 -4
  46. package/src/pi/path.ts +16 -2
  47. package/src/pi/pi.test.ts +4 -3
  48. package/src/pi/read-tool.ts +59 -27
  49. package/src/pi/read.test.ts +361 -0
  50. package/src/pi/registration.test.ts +121 -4
  51. package/src/pi/render.test.ts +172 -15
  52. package/src/pi/render.ts +28 -5
  53. package/src/pi/replace-tool.ts +18 -27
  54. package/src/pi/replace.test.ts +8 -107
  55. package/src/pi/result-safety.test.ts +123 -149
  56. package/src/pi/rg-match-bytes.ts +95 -0
  57. package/src/pi/rg-process.test.ts +40 -59
  58. package/src/pi/rg-process.ts +8 -5
  59. package/src/pi/rg-text-view.ts +59 -9
  60. package/src/pi/text-stream.test.ts +153 -0
  61. package/src/pi/text-stream.ts +33 -13
  62. package/src/pi/tool-call.testing.ts +50 -0
  63. package/src/pi/tool-prompts.ts +15 -0
  64. package/src/pi/write-tool.ts +19 -26
  65. package/src/pi/write.test.ts +70 -61
  66. package/src/pi/e2e-scenarios.test.ts +0 -360
@@ -0,0 +1,98 @@
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
+ });
@@ -0,0 +1,343 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { test, type TestContext } from "node:test";
6
+ import { Type } from "typebox";
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
+ import {
18
+ createActionFusionExecutor,
19
+ type ActionFusionDetails,
20
+ type ActionFusionProgress,
21
+ type ThenRunInput,
22
+ } from "../pi/action-fusion.ts";
23
+ import { makeWriteOverride } from "../pi/write-tool.ts";
24
+
25
+ /** Exercise the default runner through a real parent tool call, with no provider traffic. */
26
+ async function openSession(
27
+ t: TestContext,
28
+ configure?: (pi: ExtensionAPI) => void,
29
+ onProgress?: (event: ActionFusionProgress) => void,
30
+ ) {
31
+ const cwd = await mkdtemp(join(tmpdir(), "hashline-fusion-session-"));
32
+ let dispose: (() => void) | undefined;
33
+ t.after(async () => {
34
+ dispose?.();
35
+ await rm(cwd, { recursive: true, force: true });
36
+ });
37
+ const modelRuntime = await ModelRuntime.create({
38
+ authPath: join(cwd, "auth.json"),
39
+ modelsPath: null,
40
+ modelsStorePath: join(cwd, "models.json"),
41
+ refreshOnCreate: false,
42
+ allowModelNetwork: false,
43
+ });
44
+ modelRuntime.registerProvider("fusion-test", {
45
+ api: "openai-completions",
46
+ baseUrl: "https://unused.invalid",
47
+ apiKey: "local-test-placeholder",
48
+ models: [
49
+ {
50
+ id: "test",
51
+ name: "Test",
52
+ input: ["text"],
53
+ reasoning: false,
54
+ contextWindow: 100_000,
55
+ maxTokens: 1000,
56
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
57
+ },
58
+ ],
59
+ });
60
+ const model = modelRuntime.getModel("fusion-test", "test");
61
+ assert.ok(model);
62
+ const calls: { name: string; parent?: string }[] = [];
63
+ const progress: ActionFusionProgress[] = [];
64
+ const settingsManager = SettingsManager.inMemory({
65
+ compaction: { enabled: false },
66
+ retry: { enabled: false },
67
+ });
68
+ const loader = new DefaultResourceLoader({
69
+ cwd,
70
+ agentDir: cwd,
71
+ settingsManager,
72
+ noExtensions: true,
73
+ noSkills: true,
74
+ noPromptTemplates: true,
75
+ noThemes: true,
76
+ noContextFiles: true,
77
+ extensionFactories: [
78
+ (pi) => {
79
+ pi.on("tool_call", (event) => {
80
+ calls.push({ name: event.toolName, parent: event.parentToolCallId });
81
+ });
82
+ configure?.(pi);
83
+ pi.registerTool(
84
+ makeWriteOverride(
85
+ cwd,
86
+ createActionFusionExecutor(undefined, (event) => {
87
+ progress.push(event);
88
+ onProgress?.(event);
89
+ }),
90
+ ),
91
+ );
92
+ },
93
+ ],
94
+ });
95
+ await loader.reload();
96
+ const { session, extensionsResult } = await createAgentSession({
97
+ cwd,
98
+ agentDir: cwd,
99
+ modelRuntime,
100
+ model,
101
+ settingsManager,
102
+ resourceLoader: loader,
103
+ sessionManager: SessionManager.inMemory(cwd),
104
+ tools: ["write", "bash"],
105
+ });
106
+ dispose = () => session.dispose();
107
+ assert.deepEqual(extensionsResult.errors, []);
108
+ await session.bindExtensions({});
109
+ return {
110
+ cwd,
111
+ calls,
112
+ progress,
113
+ abort: () => session.abort(),
114
+ async run(thenRun: ThenRunInput) {
115
+ let responses = 0;
116
+ session.agent.streamFunction = () => {
117
+ const first = responses++ === 0;
118
+ assert.ok(responses <= 2, "Unexpected model request");
119
+ const message: AssistantMessage = {
120
+ role: "assistant",
121
+ content: first
122
+ ? [
123
+ {
124
+ type: "toolCall",
125
+ id: "fused",
126
+ name: "write",
127
+ arguments: {
128
+ path: "saved.txt",
129
+ mode: "create",
130
+ content: "saved\n",
131
+ then_run: thenRun,
132
+ },
133
+ },
134
+ ]
135
+ : [{ type: "text", text: "Done." }],
136
+ stopReason: first ? "toolUse" : "stop",
137
+ api: model.api,
138
+ provider: model.provider,
139
+ model: model.id,
140
+ timestamp: Date.now(),
141
+ usage: {
142
+ input: 0,
143
+ output: 0,
144
+ cacheRead: 0,
145
+ cacheWrite: 0,
146
+ totalTokens: 0,
147
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
148
+ },
149
+ };
150
+ const stream = new AssistantMessageEventStream();
151
+ stream.push({ type: "start", partial: message });
152
+ stream.push({ type: "done", reason: first ? "toolUse" : "stop", message });
153
+ return stream;
154
+ };
155
+ await session.prompt("Run the requested local command after the mutation.");
156
+ assert.equal(session.agent.state.errorMessage, undefined);
157
+ const result = session.agent.state.messages.find(
158
+ (message) => message.role === "toolResult" && message.toolCallId === "fused",
159
+ );
160
+ assert.ok(result?.role === "toolResult");
161
+ assert.equal(result.isError, false, "A command failure must not fail the completed mutation");
162
+ assert.equal(await readFile(join(cwd, "saved.txt"), "utf8"), "saved\n");
163
+ return {
164
+ modelRequests: responses,
165
+ state: (result.details as unknown as { actionFusion: ActionFusionDetails }).actionFusion,
166
+ text: result.content
167
+ .filter((block) => block.type === "text")
168
+ .map((block) => block.text)
169
+ .join("\n"),
170
+ };
171
+ },
172
+ };
173
+ }
174
+
175
+ const commandCases: {
176
+ name: string;
177
+ source: string;
178
+ timeout?: number;
179
+ command: ActionFusionDetails["command"];
180
+ diagnostic: RegExp;
181
+ }[] = [
182
+ {
183
+ name: "successful exit",
184
+ source: "console.log('checked');",
185
+ command: "succeeded",
186
+ diagnostic: /checked/,
187
+ },
188
+ {
189
+ name: "nonzero exit with timeout in its output",
190
+ source: "console.error('timeout regression failed'); process.exit(1);",
191
+ command: "failed",
192
+ diagnostic: /Command exited with code 1/,
193
+ },
194
+ {
195
+ name: "nonzero exit with a timeout-shaped log line",
196
+ source: "console.error('Command timed out after 60 seconds'); process.exit(7);",
197
+ timeout: 60,
198
+ command: "failed",
199
+ diagnostic: /Command exited with code 7/,
200
+ },
201
+ {
202
+ name: "actual timeout",
203
+ source: "setTimeout(() => {}, 10_000);",
204
+ timeout: 0.2,
205
+ command: "timeout",
206
+ diagnostic: /Command timed out after 0\.2 seconds/,
207
+ },
208
+ ];
209
+ for (const { name, source, timeout, command, diagnostic } of commandCases) {
210
+ test(`real session ${name} → preserves the command outcome and published file`, {
211
+ timeout: 15_000,
212
+ }, async (t) => {
213
+ const f = await openSession(t);
214
+ await writeFile(join(f.cwd, "command.mjs"), source);
215
+ const result = await f.run({
216
+ command: "node command.mjs",
217
+ ...(timeout === undefined ? {} : { timeout }),
218
+ });
219
+ assert.deepEqual(result.state, { publication: "PUBLISHED", command, freshness: "unchanged" });
220
+ assert.match(result.text, diagnostic);
221
+ assert.equal(f.progress.at(-1)?.command, command);
222
+ });
223
+ }
224
+
225
+ test("cancelling a real session Bash command → reports cancellation and keeps the published mutation", {
226
+ timeout: 15_000,
227
+ }, async (t) => {
228
+ const started = Promise.withResolvers<void>();
229
+ const f = await openSession(t, undefined, (event) => {
230
+ if (event.command === "running" && event.output.includes("READY")) started.resolve();
231
+ });
232
+ await writeFile(
233
+ join(f.cwd, "command.mjs"),
234
+ "console.log('READY'); setInterval(() => {}, 1000);\n",
235
+ );
236
+ const pending = f.run({ command: "node command.mjs" });
237
+ await started.promise;
238
+ await f.abort();
239
+ const result = await pending;
240
+ assert.deepEqual(result.state, {
241
+ publication: "PUBLISHED",
242
+ command: "cancelled",
243
+ freshness: "unchanged",
244
+ });
245
+ assert.match(result.text, /Command aborted/);
246
+ assert.equal(f.progress.at(-1)?.command, "cancelled");
247
+ });
248
+
249
+ test("session Bash permission checks wait → countdown starts with command execution progress", {
250
+ timeout: 15_000,
251
+ }, async (t) => {
252
+ const checking = Promise.withResolvers<void>();
253
+ const allowed = Promise.withResolvers<void>();
254
+ const f = await openSession(t, (pi) => {
255
+ pi.on("tool_call", async (event) => {
256
+ if (event.toolName === "bash") {
257
+ checking.resolve();
258
+ await allowed.promise;
259
+ }
260
+ });
261
+ });
262
+ await writeFile(join(f.cwd, "command.mjs"), "console.log('checked');\n");
263
+ const pending = f.run({ command: "node command.mjs", timeout: 10 });
264
+ try {
265
+ await checking.promise;
266
+ assert.ok(f.progress.every((event) => event.timing === undefined));
267
+ } finally {
268
+ allowed.resolve();
269
+ await pending;
270
+ }
271
+ assert.deepEqual(f.progress.find((event) => event.timing)?.timing, {
272
+ timeoutSeconds: 10,
273
+ remainingSeconds: 10,
274
+ });
275
+ assert.equal(f.progress.at(-1)?.command, "succeeded");
276
+ });
277
+
278
+ test("session Bash tool_call blocks then_run → no command side effect, mutation stays published", {
279
+ timeout: 15_000,
280
+ }, async (t) => {
281
+ const f = await openSession(t, (pi) => {
282
+ pi.on("tool_call", (event) =>
283
+ event.toolName === "bash"
284
+ ? { block: true, reason: "BLOCKED_BY_POLICY", terminate: true }
285
+ : undefined,
286
+ );
287
+ });
288
+ await writeFile(
289
+ join(f.cwd, "command.mjs"),
290
+ "import { writeFileSync } from 'node:fs'; writeFileSync('command-ran', 'yes');\n",
291
+ );
292
+ const result = await f.run({ command: "node command.mjs" });
293
+ assert.deepEqual(result.state, {
294
+ publication: "PUBLISHED",
295
+ command: "failed",
296
+ freshness: "unchanged",
297
+ });
298
+ assert.match(result.text, /BLOCKED_BY_POLICY/);
299
+ assert.equal(result.modelRequests, 1, "Preserve the policy hook's request to stop the batch");
300
+ await assert.rejects(readFile(join(f.cwd, "command-ran")), { code: "ENOENT" });
301
+ assert.ok(f.calls.some((call) => call.name === "bash" && call.parent === "fused"));
302
+ });
303
+
304
+ test("session Bash override and tool_result hook → then_run uses their final result", {
305
+ timeout: 15_000,
306
+ }, async (t) => {
307
+ let executions = 0;
308
+ const f = await openSession(t, (pi) => {
309
+ pi.registerTool({
310
+ name: "bash",
311
+ label: "bash",
312
+ description: "Session Bash override",
313
+ parameters: Type.Object({ command: Type.String() }),
314
+ async execute() {
315
+ executions++;
316
+ return { content: [{ type: "text", text: "OVERRIDE_RESULT" }], details: {} };
317
+ },
318
+ });
319
+ pi.on("tool_result", (event) =>
320
+ event.toolName === "bash"
321
+ ? {
322
+ content: [{ type: "text", text: "HOOK_REJECTED_OVERRIDE" }],
323
+ isError: true,
324
+ }
325
+ : undefined,
326
+ );
327
+ });
328
+ await writeFile(
329
+ join(f.cwd, "command.mjs"),
330
+ "import { writeFileSync } from 'node:fs'; writeFileSync('command-ran', 'yes');\n",
331
+ );
332
+ const result = await f.run({ command: "node command.mjs" });
333
+ assert.equal(executions, 1);
334
+ assert.deepEqual(result.state, {
335
+ publication: "PUBLISHED",
336
+ command: "failed",
337
+ freshness: "unchanged",
338
+ });
339
+ assert.match(result.text, /HOOK_REJECTED_OVERRIDE/);
340
+ assert.doesNotMatch(result.text, /OVERRIDE_RESULT/);
341
+ await assert.rejects(readFile(join(f.cwd, "command-ran")), { code: "ENOENT" });
342
+ assert.ok(f.calls.some((call) => call.name === "bash" && call.parent === "fused"));
343
+ });