@criogaid/pi-hashline-edit 0.3.1 → 0.4.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 (69) hide show
  1. package/README.md +58 -49
  2. package/package.json +8 -3
  3. package/src/core/apply.test.ts +366 -310
  4. package/src/core/apply.ts +269 -202
  5. package/src/core/hash.test.ts +61 -23
  6. package/src/core/hash.ts +45 -16
  7. package/src/core/lines.test.ts +46 -27
  8. package/src/core/lines.ts +36 -28
  9. package/src/core/ranges.test.ts +73 -19
  10. package/src/core/ranges.ts +15 -15
  11. package/src/core/text.test.ts +3 -3
  12. package/src/core/text.ts +28 -9
  13. package/src/core/types.ts +54 -36
  14. package/src/index.ts +22 -16
  15. package/src/integration/grep-rg.test.ts +834 -219
  16. package/src/integration/large-text.test.ts +62 -0
  17. package/src/integration/replace-package.test.ts +37 -0
  18. package/src/pi/action-fusion.test.ts +535 -206
  19. package/src/pi/action-fusion.ts +469 -244
  20. package/src/pi/anchor-format.test.ts +30 -19
  21. package/src/pi/anchor-format.ts +27 -14
  22. package/src/pi/budgets.ts +20 -0
  23. package/src/pi/config.test.ts +60 -30
  24. package/src/pi/config.ts +45 -32
  25. package/src/pi/directory-sync.test.ts +55 -0
  26. package/src/pi/e2e-scenarios.test.ts +359 -0
  27. package/src/pi/edit-tool.ts +426 -262
  28. package/src/pi/error-text.ts +21 -0
  29. package/src/pi/execute.test.ts +1593 -712
  30. package/src/pi/failure-context.test.ts +105 -83
  31. package/src/pi/failure-context.ts +83 -71
  32. package/src/pi/failure-path.test.ts +171 -64
  33. package/src/pi/file-commit.test.ts +446 -233
  34. package/src/pi/file-commit.ts +347 -203
  35. package/src/pi/fusion-card.test.ts +118 -83
  36. package/src/pi/fusion-card.ts +120 -85
  37. package/src/pi/grep-output.ts +208 -0
  38. package/src/pi/grep-render.ts +58 -0
  39. package/src/pi/grep-scope.ts +152 -0
  40. package/src/pi/grep-search.ts +217 -0
  41. package/src/pi/grep-tool.ts +191 -766
  42. package/src/pi/grep.test.ts +562 -150
  43. package/src/pi/mutation-result.test.ts +37 -0
  44. package/src/pi/mutation-result.ts +107 -59
  45. package/src/pi/mutation-runner.ts +168 -0
  46. package/src/pi/path.ts +20 -12
  47. package/src/pi/pi.test.ts +95 -52
  48. package/src/pi/read-tool.ts +215 -132
  49. package/src/pi/registration.test.ts +274 -113
  50. package/src/pi/render.test.ts +218 -83
  51. package/src/pi/render.ts +152 -95
  52. package/src/pi/replace-apply.ts +109 -0
  53. package/src/pi/replace-tool.ts +280 -240
  54. package/src/pi/replace-worker.mjs +4 -0
  55. package/src/pi/replace-worker.ts +10 -0
  56. package/src/pi/replace.test.ts +773 -389
  57. package/src/pi/result-safety.test.ts +779 -342
  58. package/src/pi/rg-line-filter.test.ts +64 -36
  59. package/src/pi/rg-line-filter.ts +40 -124
  60. package/src/pi/rg-line-ranges.test.ts +57 -31
  61. package/src/pi/rg-line-ranges.ts +44 -82
  62. package/src/pi/rg-text-view.ts +106 -36
  63. package/src/pi/schema.ts +27 -0
  64. package/src/pi/state.ts +7 -7
  65. package/src/pi/text-stream.test.ts +118 -0
  66. package/src/pi/text-stream.ts +136 -0
  67. package/src/pi/tool-call.testing.ts +37 -0
  68. package/src/pi/write-tool.ts +115 -52
  69. package/src/pi/write.test.ts +248 -96
@@ -9,120 +9,281 @@ import { initTheme } from "@earendil-works/pi-coding-agent";
9
9
  import { ToolExecutionComponent } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/tool-execution.js";
10
10
  import { theme } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/theme/theme.js";
11
11
  import { computeLineHash } from "../core/hash.ts";
12
+ import { callTool } from "./tool-call.testing.ts";
12
13
 
13
14
  test("mutation cards use Fusion by default and explicit false removes command support", async () => {
14
- const dir = await mkdtemp(join(tmpdir(), "hashline-registration-"));
15
- const previousCwd = process.cwd();
16
- const state = getState();
17
- const previousConfig = state.config;
18
- try {
19
- await mkdir(join(dir, ".pi"));
20
- await writeFile(join(dir, ".pi", "settings.json"), JSON.stringify({ hashlineEdit: { enabled: true } }));
21
- process.chdir(dir);
22
- const tools: any[] = [];
23
- const entries: any[] = [];
24
- const renderers = new Map<string, any>();
25
- registerHashline({
26
- on() {},
27
- registerEntryRenderer(type: string, renderer: any) { renderers.set(type, renderer); },
28
- appendEntry(customType: string, data: unknown) { entries.push({ customType, data }); },
29
- registerTool(tool: any) { tools.push(tool); },
30
- } as any);
31
- assert.deepEqual(tools.map((tool) => tool.name), ["write", "edit", "replace", "read", "grep"]);
32
- for (const tool of tools.filter((tool) => ["edit", "replace", "write"].includes(tool.name))) {
33
- assert.ok(tool.parameters.properties.then_run, `${tool.name} should expose then_run when actionFusion is enabled`);
34
- }
35
- initTheme("dark");
36
- const cases = [
37
- { name: "write", args: { content: "published\n" } },
38
- { name: "edit", args: { edits: [{ op: "append", body: ["appended"] }] } },
39
- { name: "replace", args: { find: "published", replace: "published" } },
40
- ];
41
- for (const { name, args } of cases) {
42
- const tool = tools.find((tool) => tool.name === name);
43
- const params = { path: "published.txt", ...args, then_run: { command: "exit 7" } };
44
- const card = new ToolExecutionComponent(name, name, params, {}, tool, { requestRender() {} } as any, dir);
45
- card.setArgsComplete();
46
- card.markExecutionStarted();
47
- const frames: { command: string; publication: string; mutationCompleted: boolean; output: string; commandOutput: string }[] = [];
48
- const result = await tool.execute(name, params, undefined, (update: any) => {
49
- card.updateResult({ ...update, isError: false }, true);
50
- const entry = entries.find((entry) => entry.customType === "hashline-then-run" && entry.data.toolCallId === name);
51
- const commandCard = renderers.get(entry.customType)(entry, { expanded: false }, theme);
52
- frames.push({ ...update.details.actionFusion, output: card.render(100).join("\n"), commandOutput: commandCard.render(100).join("\n") });
53
- }, { cwd: dir });
54
- assert.equal(result.details.actionFusion.command, "failed");
55
- assert.match(result.content[1].text, /File changes are saved|No file changes were published/);
56
- assert.ok(frames[0].output.includes(theme.getBgAnsi("toolPendingBg")));
57
- const running = frames.find((frame) => frame.command === "running")!;
58
- assert.ok(running, `${name} should emit running progress`);
59
- assert.ok(running.output.includes(theme.getBgAnsi("toolSuccessBg")), `${name} should turn green before then_run ends`);
60
- assert.ok(!running.output.includes(theme.getBgAnsi("toolPendingBg")));
61
- assert.ok(running.commandOutput.includes(theme.getBgAnsi("toolPendingBg")));
62
- assert.ok(frames.at(-1)!.commandOutput.includes(theme.getBgAnsi("toolErrorBg")));
63
- const completed = frames.find((frame) => frame.command === "waiting" && frame.mutationCompleted)!;
64
- assert.ok(completed?.output.includes(theme.getBgAnsi("toolSuccessBg")), "mutation completion must repaint before command checks");
65
- if (name === "replace") assert.equal(running.publication, "NOT_PUBLISHED");
66
- card.updateResult({ ...result, isError: false });
67
- assert.ok(card.render(100).join("\n").includes(theme.getBgAnsi("toolSuccessBg")));
68
- card.setExpanded(true);
69
- assert.doesNotMatch(card.render(100).join("\n"), /publication=|freshness=/);
70
- assert.doesNotMatch(card.render(100).join("\n"), /Command exited|then_run:failed/);
71
- assert.doesNotMatch(frames.at(-1)!.commandOutput, /publication=|freshness=|File changes are saved|No file changes were published|mutation completed/);
72
- assert.ok(card.render(100).join("\n").includes(theme.getBgAnsi("toolSuccessBg")));
15
+ const dir = await mkdtemp(join(tmpdir(), "hashline-registration-"));
16
+ const previousCwd = process.cwd();
17
+ const state = getState();
18
+ const previousConfig = state.config;
19
+ try {
20
+ await mkdir(join(dir, ".pi"));
21
+ await writeFile(
22
+ join(dir, ".pi", "settings.json"),
23
+ JSON.stringify({ hashlineEdit: { enabled: true } }),
24
+ );
25
+ process.chdir(dir);
26
+ const tools: any[] = [];
27
+ const entries: any[] = [];
28
+ const renderers = new Map<string, any>();
29
+ registerHashline({
30
+ on() {},
31
+ registerEntryRenderer(type: string, renderer: any) {
32
+ renderers.set(type, renderer);
33
+ },
34
+ appendEntry(customType: string, data: unknown) {
35
+ entries.push({ customType, data });
36
+ },
37
+ registerTool(tool: any) {
38
+ tools.push(tool);
39
+ },
40
+ } as any);
41
+ assert.deepEqual(
42
+ tools.map((tool) => tool.name),
43
+ ["write", "edit", "replace", "read", "grep"],
44
+ );
45
+ const grep = tools.find((tool) => tool.name === "grep");
46
+ assert.deepEqual(Object.keys(grep.parameters.properties).sort(), [
47
+ "context",
48
+ "glob",
49
+ "ignoreCase",
50
+ "limit",
51
+ "literal",
52
+ "multiline",
53
+ "outputMode",
54
+ "path",
55
+ "pattern",
56
+ ]);
57
+ assert.equal(grep.parameters.additionalProperties, false);
58
+ await assert.rejects(
59
+ callTool(grep, { pattern: "needle", noIgnore: false }),
60
+ /Validation failed for tool "grep":\n {2}- noIgnore: schema is false/,
61
+ );
62
+ for (const tool of tools.filter((tool) => ["edit", "replace", "write"].includes(tool.name))) {
63
+ assert.ok(
64
+ tool.parameters.properties.then_run,
65
+ `${tool.name} should expose then_run when actionFusion is enabled`,
66
+ );
67
+ }
68
+ initTheme("dark");
69
+ const cases = [
70
+ { name: "write", args: { content: "published\n" } },
71
+ { name: "edit", args: { edits: [{ op: "append", body: ["appended"] }] } },
72
+ { name: "replace", args: { replacements: [{ find: "published", replace: "published" }] } },
73
+ ];
74
+ for (const { name, args } of cases) {
75
+ const tool = tools.find((tool) => tool.name === name);
76
+ const params = { path: "published.txt", ...args, then_run: { command: "exit 7" } };
77
+ const card = new ToolExecutionComponent(
78
+ name,
79
+ name,
80
+ params,
81
+ {},
82
+ tool,
83
+ { requestRender() {} } as any,
84
+ dir,
85
+ );
86
+ card.setArgsComplete();
87
+ card.markExecutionStarted();
88
+ const frames: {
89
+ command: string;
90
+ publication: string;
91
+ mutationCompleted: boolean;
92
+ output: string;
93
+ commandOutput: string;
94
+ }[] = [];
95
+ const result = await tool.execute(
96
+ name,
97
+ params,
98
+ undefined,
99
+ (update: any) => {
100
+ card.updateResult({ ...update, isError: false }, true);
101
+ const entry = entries.find(
102
+ (entry) => entry.customType === "hashline-then-run" && entry.data.toolCallId === name,
103
+ );
104
+ const commandCard = renderers.get(entry.customType)(entry, { expanded: false }, theme);
105
+ frames.push({
106
+ ...update.details.actionFusion,
107
+ output: card.render(100).join("\n"),
108
+ commandOutput: commandCard.render(100).join("\n"),
109
+ });
110
+ },
111
+ { cwd: dir },
112
+ );
113
+ assert.equal(result.details.actionFusion.command, "failed");
114
+ assert.match(result.content[1].text, /File changes are saved|No file changes were published/);
115
+ assert.ok(frames[0].output.includes(theme.getBgAnsi("toolPendingBg")));
116
+ const running = frames.find((frame) => frame.command === "running")!;
117
+ assert.ok(running, `${name} should emit running progress`);
118
+ assert.ok(
119
+ running.output.includes(theme.getBgAnsi("toolSuccessBg")),
120
+ `${name} should turn green before then_run ends`,
121
+ );
122
+ assert.ok(!running.output.includes(theme.getBgAnsi("toolPendingBg")));
123
+ assert.ok(running.commandOutput.includes(theme.getBgAnsi("toolPendingBg")));
124
+ assert.ok(frames.at(-1)!.commandOutput.includes(theme.getBgAnsi("toolErrorBg")));
125
+ const completed = frames.find(
126
+ (frame) => frame.command === "waiting" && frame.mutationCompleted,
127
+ )!;
128
+ assert.ok(
129
+ completed?.output.includes(theme.getBgAnsi("toolSuccessBg")),
130
+ "mutation completion must repaint before command checks",
131
+ );
132
+ if (name === "replace") assert.equal(running.publication, "NOT_PUBLISHED");
133
+ card.updateResult({ ...result, isError: false });
134
+ assert.ok(card.render(100).join("\n").includes(theme.getBgAnsi("toolSuccessBg")));
135
+ card.setExpanded(true);
136
+ assert.doesNotMatch(card.render(100).join("\n"), /publication=|freshness=/);
137
+ assert.doesNotMatch(card.render(100).join("\n"), /Command exited|then_run:failed/);
138
+ assert.doesNotMatch(
139
+ frames.at(-1)!.commandOutput,
140
+ /publication=|freshness=|File changes are saved|No file changes were published|mutation completed/,
141
+ );
142
+ assert.ok(card.render(100).join("\n").includes(theme.getBgAnsi("toolSuccessBg")));
73
143
 
74
- const invalid = { ...params, path: "missing.txt", ...(name === "write" ? { mode: "overwrite" } : {}) };
75
- const failedCard = new ToolExecutionComponent(name, `${name}-bad`, invalid, {}, tool, { requestRender() {} } as any, dir);
76
- await assert.rejects(tool.execute(`${name}-bad`, invalid, undefined, (update: any) => {
77
- failedCard.updateResult({ ...update, isError: false }, true);
78
- }, { cwd: dir }), (error: Error) => {
79
- failedCard.updateResult({ content: [{ type: "text", text: error.message }], isError: true });
80
- const output = failedCard.render(100).join("\n");
81
- assert.ok(output.includes(theme.getBgAnsi("toolErrorBg")), `${name} mutation failure should turn red`);
82
- assert.ok(!output.includes(theme.getBgAnsi("toolPendingBg")));
83
- assert.doesNotMatch(output, /the command was not run|then_run:skipped/);
84
- assert.match(output, name === "write" ? /does not exist/ : /Error reading/);
85
- const entry = entries.find((entry) => entry.customType === "hashline-then-run" && entry.data.toolCallId === `${name}-bad`);
86
- const commandOutput = renderers.get(entry.customType)(entry, { expanded: true }, theme).render(160).join("\n");
87
- assert.match(commandOutput, /skipped[\s\S]*Not run because the mutation did not complete/);
88
- assert.doesNotMatch(commandOutput, /Error reading|does not exist|publication=|freshness=/);
89
- assert.ok(!commandOutput.includes(theme.getBgAnsi("toolErrorBg")));
90
- return true;
91
- });
92
- }
93
- assert.deepEqual(entries.map((entry) => entry.data.command), cases.flatMap(() => ["waiting", "failed", "waiting", "skipped"]));
94
- assert.ok(entries.every((entry) => !("publication" in entry.data) && !("freshness" in entry.data) && !("path" in entry.data)));
95
- await writeFile(join(dir, "stale.txt"), "header\ntarget\n");
96
- const edit = tools.find((tool) => tool.name === "edit");
97
- const stale = { path: "stale.txt", edits: [{ op: "replace", anchor: `1#${computeLineHash(1, "target")}`, body: ["changed"] }], then_run: { command: "exit 99" } };
98
- const staleCard = new ToolExecutionComponent("edit", "stale", stale, {}, edit, { requestRender() {} } as any, dir);
99
- await assert.rejects(edit.execute("stale", stale, undefined, (update: any) => staleCard.updateResult({ ...update, isError: false }, true), { cwd: dir }), (error: Error) => {
100
- assert.match(error.message, /checksum-matching candidate[\s\S]*Input-anchor checks/);
101
- staleCard.updateResult({ content: [{ type: "text", text: error.message }], isError: true });
102
- assert.match(staleCard.render(160).join("\n"), /Anchor mismatch/);
103
- const entry = entries.find((entry) => entry.customType === "hashline-then-run" && entry.data.toolCallId === "stale");
104
- const commandOutput = renderers.get(entry.customType)(entry, { expanded: true }, theme).render(160).join("\n");
105
- assert.match(commandOutput, /skipped/);
106
- assert.doesNotMatch(commandOutput, /Anchor mismatch|candidate|Input-anchor|publication=|freshness=/);
107
- return true;
108
- });
109
- assert.equal(await readFile(join(dir, "stale.txt"), "utf8"), "header\ntarget\n");
110
- await writeFile(join(dir, ".pi", "settings.json"), JSON.stringify({ hashlineEdit: { actionFusion: false } }));
111
- const disabledTools: any[] = [];
112
- registerHashline({
113
- on() {},
114
- registerEntryRenderer() {},
115
- registerTool(tool: any) { disabledTools.push(tool); },
116
- } as any);
117
- assert.equal(disabledTools.length, 5);
118
- for (const tool of disabledTools.filter((tool) => ["edit", "replace", "write"].includes(tool.name))) {
119
- assert.equal(tool.parameters.properties.then_run, undefined);
120
- assert.equal(tool.renderShell, "default");
121
- await assert.rejects(tool.execute("disabled", { path: "published.txt", then_run: { command: "exit 0" } }, undefined, undefined, { cwd: dir }), /then_run is unavailable/);
122
- }
123
- } finally {
124
- process.chdir(previousCwd);
125
- state.config = previousConfig;
126
- await rm(dir, { recursive: true, force: true });
127
- }
144
+ const invalid = {
145
+ ...params,
146
+ path: "missing.txt",
147
+ ...(name === "write" ? { mode: "overwrite" } : {}),
148
+ };
149
+ const failedCard = new ToolExecutionComponent(
150
+ name,
151
+ `${name}-bad`,
152
+ invalid,
153
+ {},
154
+ tool,
155
+ { requestRender() {} } as any,
156
+ dir,
157
+ );
158
+ await assert.rejects(
159
+ tool.execute(
160
+ `${name}-bad`,
161
+ invalid,
162
+ undefined,
163
+ (update: any) => {
164
+ failedCard.updateResult({ ...update, isError: false }, true);
165
+ },
166
+ { cwd: dir },
167
+ ),
168
+ (error: Error) => {
169
+ failedCard.updateResult({
170
+ content: [{ type: "text", text: error.message }],
171
+ isError: true,
172
+ });
173
+ const output = failedCard.render(100).join("\n");
174
+ assert.ok(
175
+ output.includes(theme.getBgAnsi("toolErrorBg")),
176
+ `${name} mutation failure should turn red`,
177
+ );
178
+ assert.ok(!output.includes(theme.getBgAnsi("toolPendingBg")));
179
+ assert.doesNotMatch(output, /the command was not run|then_run:skipped/);
180
+ assert.match(output, name === "write" ? /does not exist/ : /Error reading/);
181
+ const entry = entries.find(
182
+ (entry) =>
183
+ entry.customType === "hashline-then-run" && entry.data.toolCallId === `${name}-bad`,
184
+ );
185
+ const commandOutput = renderers
186
+ .get(entry.customType)(entry, { expanded: true }, theme)
187
+ .render(160)
188
+ .join("\n");
189
+ assert.match(
190
+ commandOutput,
191
+ /skipped[\s\S]*Not run because the mutation did not complete/,
192
+ );
193
+ assert.doesNotMatch(
194
+ commandOutput,
195
+ /Error reading|does not exist|publication=|freshness=/,
196
+ );
197
+ assert.ok(!commandOutput.includes(theme.getBgAnsi("toolErrorBg")));
198
+ return true;
199
+ },
200
+ );
201
+ }
202
+ assert.deepEqual(
203
+ entries.map((entry) => entry.data.command),
204
+ cases.flatMap(() => ["waiting", "failed", "waiting", "skipped"]),
205
+ );
206
+ assert.ok(
207
+ entries.every(
208
+ (entry) =>
209
+ !("publication" in entry.data) && !("freshness" in entry.data) && !("path" in entry.data),
210
+ ),
211
+ );
212
+ await writeFile(join(dir, "stale.txt"), "header\ntarget\n");
213
+ const edit = tools.find((tool) => tool.name === "edit");
214
+ const stale = {
215
+ path: "stale.txt",
216
+ edits: [{ op: "replace", anchor: `1#${computeLineHash(1, "target")}`, body: ["changed"] }],
217
+ then_run: { command: "exit 99" },
218
+ };
219
+ const staleCard = new ToolExecutionComponent(
220
+ "edit",
221
+ "stale",
222
+ stale,
223
+ {},
224
+ edit,
225
+ { requestRender() {} } as any,
226
+ dir,
227
+ );
228
+ await assert.rejects(
229
+ edit.execute(
230
+ "stale",
231
+ stale,
232
+ undefined,
233
+ (update: any) => staleCard.updateResult({ ...update, isError: false }, true),
234
+ { cwd: dir },
235
+ ),
236
+ (error: Error) => {
237
+ assert.match(error.message, /checksum-matching candidate/);
238
+ staleCard.updateResult({ content: [{ type: "text", text: error.message }], isError: true });
239
+ assert.match(staleCard.render(160).join("\n"), /Anchor mismatch/);
240
+ const entry = entries.find(
241
+ (entry) => entry.customType === "hashline-then-run" && entry.data.toolCallId === "stale",
242
+ );
243
+ const commandOutput = renderers
244
+ .get(entry.customType)(entry, { expanded: true }, theme)
245
+ .render(160)
246
+ .join("\n");
247
+ assert.match(commandOutput, /skipped/);
248
+ assert.doesNotMatch(
249
+ commandOutput,
250
+ /Anchor mismatch|candidate|Input-anchor|publication=|freshness=/,
251
+ );
252
+ return true;
253
+ },
254
+ );
255
+ assert.equal(await readFile(join(dir, "stale.txt"), "utf8"), "header\ntarget\n");
256
+ await writeFile(
257
+ join(dir, ".pi", "settings.json"),
258
+ JSON.stringify({ hashlineEdit: { actionFusion: false } }),
259
+ );
260
+ const disabledTools: any[] = [];
261
+ registerHashline({
262
+ on() {},
263
+ registerEntryRenderer() {},
264
+ registerTool(tool: any) {
265
+ disabledTools.push(tool);
266
+ },
267
+ } as any);
268
+ assert.equal(disabledTools.length, 5);
269
+ for (const tool of disabledTools.filter((tool) =>
270
+ ["edit", "replace", "write"].includes(tool.name),
271
+ )) {
272
+ assert.equal(tool.parameters.properties.then_run, undefined);
273
+ assert.equal(tool.renderShell, "default");
274
+ // Without Action Fusion the schema has no then_run, so Pi rejects it before execute.
275
+ await assert.rejects(
276
+ callTool(
277
+ tool,
278
+ { path: "published.txt", then_run: { command: "exit 0" } },
279
+ { ctx: { cwd: dir } },
280
+ ),
281
+ /Validation failed for tool "(edit|replace|write)":[\s\S]*- then_run: schema is false/,
282
+ );
283
+ }
284
+ } finally {
285
+ process.chdir(previousCwd);
286
+ state.config = previousConfig;
287
+ await rm(dir, { recursive: true, force: true });
288
+ }
128
289
  });