@criogaid/pi-hashline-edit 0.5.1 → 0.6.1

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 (53) hide show
  1. package/README.md +51 -15
  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/index.ts +2 -0
  7. package/src/integration/forget-grep.test.ts +98 -0
  8. package/src/integration/fusion-dispatch.test.ts +343 -0
  9. package/src/integration/grep-rg.test.ts +269 -33
  10. package/src/integration/mutation-file-types.test.ts +44 -0
  11. package/src/pi/action-fusion.test.ts +71 -128
  12. package/src/pi/action-fusion.ts +83 -45
  13. package/src/pi/argument-validation.test.ts +136 -0
  14. package/src/pi/argument-validation.ts +102 -0
  15. package/src/pi/budgets.ts +4 -1
  16. package/src/pi/config.test.ts +1 -0
  17. package/src/pi/config.ts +4 -0
  18. package/src/pi/directory-sync.test.ts +1 -1
  19. package/src/pi/edit-tool.ts +55 -36
  20. package/src/pi/execute.test.ts +185 -645
  21. package/src/pi/extension-loading.test.ts +34 -0
  22. package/src/pi/extension-loading.testing.ts +15 -0
  23. package/src/pi/failure-context.test.ts +4 -3
  24. package/src/pi/failure-path.test.ts +3 -3
  25. package/src/pi/file-commit.test.ts +24 -17
  26. package/src/pi/file-commit.ts +36 -9
  27. package/src/pi/file-snapshot.test.ts +24 -0
  28. package/src/pi/forget-tool.ts +268 -0
  29. package/src/pi/forget.test.ts +343 -0
  30. package/src/pi/forget.testing.ts +273 -0
  31. package/src/pi/grep-output.ts +57 -28
  32. package/src/pi/grep-search.ts +35 -12
  33. package/src/pi/grep-tool.ts +28 -9
  34. package/src/pi/grep.test.ts +173 -152
  35. package/src/pi/mutation-result.test.ts +23 -0
  36. package/src/pi/mutation-runner.ts +8 -4
  37. package/src/pi/path.ts +16 -2
  38. package/src/pi/pi.test.ts +3 -2
  39. package/src/pi/read-tool.ts +58 -26
  40. package/src/pi/read.test.ts +361 -0
  41. package/src/pi/registration.test.ts +115 -2
  42. package/src/pi/render.test.ts +45 -14
  43. package/src/pi/replace-tool.ts +18 -27
  44. package/src/pi/replace.test.ts +8 -107
  45. package/src/pi/result-safety.test.ts +123 -149
  46. package/src/pi/rg-match-bytes.ts +95 -0
  47. package/src/pi/rg-process.test.ts +40 -59
  48. package/src/pi/rg-text-view.ts +52 -5
  49. package/src/pi/tool-call.testing.ts +50 -0
  50. package/src/pi/tool-prompts.ts +15 -0
  51. package/src/pi/write-tool.ts +17 -26
  52. package/src/pi/write.test.ts +70 -61
  53. package/src/pi/e2e-scenarios.test.ts +0 -361
@@ -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
+ });