@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
@@ -8,6 +8,16 @@
8
8
  */
9
9
 
10
10
  import { validateToolArguments } from "@earendil-works/pi-ai";
11
+ import { join } from "node:path";
12
+ import type { TestContext } from "node:test";
13
+ import {
14
+ createAgentSession,
15
+ DefaultResourceLoader,
16
+ type ExtensionToolContext,
17
+ ModelRuntime,
18
+ SessionManager,
19
+ SettingsManager,
20
+ } from "@earendil-works/pi-coding-agent";
11
21
 
12
22
  interface CallableTool {
13
23
  readonly name: string;
@@ -35,3 +45,43 @@ export async function callTool(tool: CallableTool, args: unknown, options: ToolC
35
45
  });
36
46
  return tool.execute(toolCallId, validated, options.signal, options.onUpdate, options.ctx);
37
47
  }
48
+
49
+ /** Create Pi's tool context without loading user credentials or contacting a provider. */
50
+ export async function createToolContext(
51
+ cwd: string,
52
+ t: TestContext,
53
+ mode: ExtensionToolContext["mode"] = "json",
54
+ ) {
55
+ const runtime = await ModelRuntime.create({
56
+ authPath: join(cwd, "test-auth.json"),
57
+ modelsPath: null,
58
+ modelsStorePath: join(cwd, "test-models.json"),
59
+ refreshOnCreate: false,
60
+ allowModelNetwork: false,
61
+ });
62
+ const settingsManager = SettingsManager.inMemory();
63
+ const loader = new DefaultResourceLoader({
64
+ cwd,
65
+ agentDir: cwd,
66
+ settingsManager,
67
+ noExtensions: true,
68
+ noSkills: true,
69
+ noPromptTemplates: true,
70
+ noThemes: true,
71
+ noContextFiles: true,
72
+ });
73
+ await loader.reload();
74
+ const { session } = await createAgentSession({
75
+ cwd,
76
+ agentDir: cwd,
77
+ modelRuntime: runtime,
78
+ settingsManager,
79
+ resourceLoader: loader,
80
+ sessionManager: SessionManager.inMemory(cwd),
81
+ tools: [],
82
+ });
83
+ t.after(() => session.dispose());
84
+ await session.bindExtensions({});
85
+ session.extensionRunner.setUIContext(undefined, mode);
86
+ return session.extensionRunner.createToolContext("test", undefined);
87
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Model-facing guidance shared by more than one tool.
3
+ *
4
+ * Text that belongs to one tool stays next to that tool's schema, and Action
5
+ * Fusion keeps its own guidelines and then_run wording in action-fusion.ts.
6
+ * Pi's buildRules merges every active tool's promptGuidelines into one list and
7
+ * drops entries whose trimmed text repeats, so tools that share a rule list the
8
+ * same constant and the model sees it once.
9
+ *
10
+ * @module pi-hashline-edit/pi
11
+ */
12
+
13
+ /** How edit, replace, and write divide file changes; listed by all three tools. */
14
+ export const MUTATION_TOOL_GUIDELINE =
15
+ "For file changes, use edit for line or block changes, insertions, and deletions; replace for repeated literal or regex substitutions and short changes inside long lines; write for new files and whole-file rewrites.";
@@ -2,7 +2,7 @@ import { Type, type Static } from "typebox";
2
2
  import type { AgentToolResult, AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
3
3
  import {
4
4
  createWriteToolDefinition,
5
- type ExtensionContext,
5
+ type ExtensionToolContext,
6
6
  type Theme,
7
7
  type ToolRenderResultOptions,
8
8
  } from "@earendil-works/pi-coding-agent";
@@ -12,11 +12,14 @@ import {
12
12
  type ThenRunInput,
13
13
  type ActionFusionDetails,
14
14
  } from "./action-fusion.ts";
15
- import { commitFile, type CommitMode, type CommitResult } from "./file-commit.ts";
15
+ import { commitFile, type CommitResult } from "./file-commit.ts";
16
16
  import { postProcessMutation } from "./mutation-result.ts";
17
17
  import { executeMutation, type ActionFusionExecutor } from "./mutation-runner.ts";
18
- import { invalidArgument, throwIfCancelled } from "./error-text.ts";
18
+ import { MUTATION_TOOL_GUIDELINE } from "./tool-prompts.ts";
19
+ import { throwIfCancelled } from "./error-text.ts";
20
+ import { createArgumentPreparer } from "./argument-validation.ts";
19
21
  import { unwritableTextReason } from "../core/text.ts";
22
+ import { renderToolError } from "./render.ts";
20
23
 
21
24
  const writeSchema = Type.Object(
22
25
  {
@@ -24,22 +27,16 @@ const writeSchema = Type.Object(
24
27
  content: Type.String({
25
28
  description: "Complete file content, written exactly as supplied, including line endings.",
26
29
  }),
27
- mode: Type.Optional(
28
- Type.Union([
29
- Type.Literal("create", { description: "Fail if the target already exists" }),
30
- Type.Literal("overwrite", { description: "Fail if the target does not exist" }),
31
- ]),
32
- ),
30
+ mode: Type.Union([
31
+ Type.Literal("create", { description: "Fail if the target already exists" }),
32
+ Type.Literal("overwrite", { description: "Fail if the target does not exist" }),
33
+ ]),
33
34
  },
34
35
  { additionalProperties: false },
35
36
  );
36
37
 
37
38
  function createWriteSchema(actionFusion: boolean) {
38
- return withThenRunSchema(
39
- writeSchema,
40
- "Command to run after write succeeds; failure does not roll back the write.",
41
- actionFusion,
42
- );
39
+ return withThenRunSchema(writeSchema, "write", actionFusion);
43
40
  }
44
41
  type WriteParams = Static<typeof writeSchema> & { then_run?: ThenRunInput };
45
42
  type WriteDetails = CommitResult & { path: string; actionFusion?: ActionFusionDetails };
@@ -54,20 +51,15 @@ export function makeWriteOverride(cwd: string, fusion?: ActionFusionExecutor) {
54
51
  name: "write" as const,
55
52
  label: "write",
56
53
  description:
57
- "Write a whole file exactly as supplied, including LF/CRLF, so it also converts line endings. By default, creates missing files and parent directories and overwrites existing files.",
54
+ "Write a whole file exactly as supplied, including its line endings. Choose create for a new file or overwrite for an existing file. Creates missing parent directories.",
58
55
  promptSnippet: "Write complete file content to a path",
59
- promptGuidelines: [
60
- "Use write for creating new files or whole-file overwrites; for targeted changes, prefer edit or replace to preserve surrounding content.",
61
- ...(fusion ? ACTION_FUSION_GUIDELINES : []),
62
- ],
56
+ promptGuidelines: [MUTATION_TOOL_GUIDELINE, ...(fusion ? ACTION_FUSION_GUIDELINES : [])],
63
57
  parameters,
64
- /** Reject content that cannot be written as UTF-8 before Pi's schema validation; never rewrites. */
65
- prepareArguments(args: unknown): WriteParams {
58
+ prepareArguments: createArgumentPreparer("write", parameters, (args, report) => {
66
59
  const content = (args as { content?: unknown } | null)?.content;
67
60
  const reason = typeof content === "string" ? unwritableTextReason(content) : undefined;
68
- if (reason) throw invalidArgument("content", reason);
69
- return args as WriteParams;
70
- },
61
+ if (reason) report("content", reason);
62
+ }),
71
63
  renderShell: "default" as const,
72
64
  renderCall(args: WriteParams, theme: Theme, context: WriteRenderContext) {
73
65
  return builtin.renderCall!(args, theme, context);
@@ -78,6 +70,7 @@ export function makeWriteOverride(cwd: string, fusion?: ActionFusionExecutor) {
78
70
  theme: Theme,
79
71
  context: WriteRenderContext,
80
72
  ) {
73
+ if (context.isError) return renderToolError(result, theme, options.expanded);
81
74
  return builtin.renderResult!({ ...result, details: undefined }, options, theme, context);
82
75
  },
83
76
  async execute(
@@ -85,7 +78,7 @@ export function makeWriteOverride(cwd: string, fusion?: ActionFusionExecutor) {
85
78
  params: WriteParams,
86
79
  signal: AbortSignal | undefined,
87
80
  onUpdate: AgentToolUpdateCallback<WriteDetails> | undefined,
88
- ctx: ExtensionContext,
81
+ ctx: ExtensionToolContext,
89
82
  ) {
90
83
  return executeMutation<Omit<WriteParams, "then_run">, WriteDetails>(
91
84
  {
@@ -94,7 +87,7 @@ export function makeWriteOverride(cwd: string, fusion?: ActionFusionExecutor) {
94
87
  async run(mutationParams, { absolutePath, displayPath, signal }) {
95
88
  throwIfCancelled(signal, `before write; ${displayPath} was not changed.`);
96
89
  const result = await commitFile(absolutePath, mutationParams.content, {
97
- mode: mutationParams.mode as CommitMode | undefined,
90
+ mode: mutationParams.mode,
98
91
  signal,
99
92
  });
100
93
  return {
@@ -49,83 +49,73 @@ test("write rejects unwritable content before accessing a missing target", async
49
49
  withTemp(async (dir) => {
50
50
  const file = join(dir, "missing.txt");
51
51
  const tool = makeWriteOverride(dir);
52
- const valid = { path: file, content: "ready\n" };
52
+ const valid = { path: file, content: "ready\n", mode: "create" };
53
53
  assert.equal(tool.prepareArguments(valid), valid);
54
54
  for (const [content, expected] of [
55
55
  ["bad\0", /Invalid argument content: UNSUPPORTED_TEXT: NUL bytes are not editable\./],
56
56
  ["\ud800", /Invalid argument content: INVALID_UNICODE:/],
57
57
  ] as const) {
58
58
  await assert.rejects(
59
- callTool(tool, { path: file, content }, { ctx: context(dir) }),
59
+ callTool(tool, { path: file, content, mode: "create" }, { ctx: context(dir) }),
60
60
  expected,
61
61
  );
62
62
  await assert.rejects(readFile(file, "utf8"), { code: "ENOENT" });
63
63
  }
64
64
  }));
65
65
 
66
- test("write preserves native default create/overwrite behavior", async () =>
66
+ test("write omits mode → rejects before changing files or running commands", async () =>
67
67
  withTemp(async (dir) => {
68
- const write = makeWriteOverride(dir) as any;
69
- const target = join(dir, "file.txt");
70
- const created = await write.execute(
71
- "create",
72
- { path: "file.txt", content: "one\n" },
73
- undefined,
74
- undefined,
75
- context(dir),
76
- );
77
- assert.doesNotMatch(created.content[0].text, /Revision:|[0-9a-f]{64}/);
78
- assert.equal(created.details.publishedRevision, await fileRevision(target));
79
- assert.equal("revision" in created.details, false);
80
- assert.equal(await readFile(target, "utf8"), "one\n");
81
- await write.execute(
82
- "overwrite",
83
- { path: "file.txt", content: "two\n" },
84
- undefined,
85
- undefined,
86
- context(dir),
87
- );
88
- assert.equal(await readFile(target, "utf8"), "two\n");
68
+ const existing = join(dir, "existing.txt");
69
+ const missingParent = join(dir, "missing");
70
+ const missing = join(missingParent, "new.txt");
71
+ await writeFile(existing, "original\n");
72
+ let commandRuns = 0;
73
+ const fusion = createActionFusionExecutor(async () => {
74
+ commandRuns++;
75
+ return { status: "succeeded", output: "checked" };
76
+ });
77
+ for (const executor of [undefined, fusion]) {
78
+ const tool = makeWriteOverride(dir, executor);
79
+ for (const path of [existing, missing]) {
80
+ await assert.rejects(
81
+ callTool(
82
+ tool,
83
+ { path, content: "changed\n", ...(executor ? { then_run: { command: "check" } } : {}) },
84
+ { ctx: context(dir) },
85
+ ),
86
+ /\n {2}- mode:/,
87
+ );
88
+ }
89
+ }
90
+ assert.equal(await readFile(existing, "utf8"), "original\n");
91
+ await assert.rejects(readFile(missingParent), { code: "ENOENT" });
92
+ assert.equal(commandRuns, 0);
89
93
  }));
90
94
 
91
95
  test("write supports create-only and overwrite-only modes", async () =>
92
96
  withTemp(async (dir) => {
93
- const write = makeWriteOverride(dir) as any;
94
- await write.execute(
95
- "create",
97
+ const write = makeWriteOverride(dir);
98
+ const target = join(dir, "new.txt");
99
+ const options = { ctx: context(dir) };
100
+ const created = await callTool(
101
+ write,
96
102
  { path: "new.txt", content: "new\n", mode: "create" },
97
- undefined,
98
- undefined,
99
- context(dir),
103
+ options,
100
104
  );
105
+ assert.doesNotMatch(created.content[0].text, /Revision:|[0-9a-f]{64}/);
106
+ assert.equal(created.details.publishedRevision, await fileRevision(target));
107
+ assert.equal("revision" in created.details, false);
101
108
  await assert.rejects(
102
- write.execute(
103
- "create-again",
104
- { path: "new.txt", content: "bad\n", mode: "create" },
105
- undefined,
106
- undefined,
107
- context(dir),
108
- ),
109
+ callTool(write, { path: "new.txt", content: "bad\n", mode: "create" }, options),
109
110
  /already exists/,
110
111
  );
112
+ assert.equal(await readFile(target, "utf8"), "new\n");
111
113
  await assert.rejects(
112
- write.execute(
113
- "missing-overwrite",
114
- { path: "missing.txt", content: "bad\n", mode: "overwrite" },
115
- undefined,
116
- undefined,
117
- context(dir),
118
- ),
114
+ callTool(write, { path: "missing.txt", content: "bad\n", mode: "overwrite" }, options),
119
115
  /does not exist/,
120
116
  );
121
- await write.execute(
122
- "overwrite",
123
- { path: "new.txt", content: "updated\n", mode: "overwrite" },
124
- undefined,
125
- undefined,
126
- context(dir),
127
- );
128
- assert.equal(await readFile(join(dir, "new.txt"), "utf8"), "updated\n");
117
+ await callTool(write, { path: "new.txt", content: "updated\n", mode: "overwrite" }, options);
118
+ assert.equal(await readFile(target, "utf8"), "updated\n");
129
119
  }));
130
120
 
131
121
  test("write rejects obsolete expectedRevision without overwriting", async () =>
@@ -135,6 +125,7 @@ test("write rejects obsolete expectedRevision without overwriting", async () =>
135
125
  const params = {
136
126
  path: target,
137
127
  content: "changed\n",
128
+ mode: "overwrite",
138
129
  expectedRevision: await fileRevision(target),
139
130
  };
140
131
  for (const fusion of [undefined, createActionFusionExecutor()]) {
@@ -158,7 +149,7 @@ test("write returns only a summary for empty, short, and long content", async ()
158
149
  const path = `file-${index}.txt`;
159
150
  const result = await makeWriteOverride(dir).execute(
160
151
  "write",
161
- { path, content },
152
+ { path, content, mode: "create" },
162
153
  undefined,
163
154
  undefined,
164
155
  context(dir),
@@ -170,11 +161,19 @@ test("write returns only a summary for empty, short, and long content", async ()
170
161
 
171
162
  test("write returns its summary and command output after an unchanged then_run", async () =>
172
163
  withTemp(async (dir) => {
173
- const fusion = createActionFusionExecutor(async () => "checked");
164
+ const fusion = createActionFusionExecutor(async () => ({
165
+ status: "succeeded",
166
+ output: "checked",
167
+ }));
174
168
  const write = makeWriteOverride(dir, fusion) as any;
175
169
  const result = await write.execute(
176
170
  "unchanged",
177
- { path: "unchanged.txt", content: "mutation\n", then_run: { command: "check" } },
171
+ {
172
+ path: "unchanged.txt",
173
+ content: "mutation\n",
174
+ mode: "create",
175
+ then_run: { command: "check" },
176
+ },
178
177
  undefined,
179
178
  undefined,
180
179
  context(dir),
@@ -191,12 +190,17 @@ test("write reports changed freshness when then_run changes the target", async (
191
190
  const target = join(dir, "changed.txt");
192
191
  const fusion = createActionFusionExecutor(async () => {
193
192
  await writeFile(target, "command changed\n");
194
- return "checked";
193
+ return { status: "succeeded", output: "checked" };
195
194
  });
196
195
  const write = makeWriteOverride(dir, fusion) as any;
197
196
  const result = await callTool(
198
197
  write,
199
- { path: "changed.txt", content: "mutation\n", then_run: { command: "check" } },
198
+ {
199
+ path: "changed.txt",
200
+ content: "mutation\n",
201
+ mode: "create",
202
+ then_run: { command: "check" },
203
+ },
200
204
  { toolCallId: "changed", ctx: context(dir) },
201
205
  );
202
206
  const text = result.content.map((block: any) => block.text).join("\n");
@@ -219,11 +223,16 @@ test("write reports missing freshness when then_run removes the target", async (
219
223
  const target = join(dir, "missing.txt");
220
224
  const fusion = createActionFusionExecutor(async () => {
221
225
  await rm(target);
222
- return "removed";
226
+ return { status: "succeeded", output: "removed" };
223
227
  });
224
228
  const result = await makeWriteOverride(dir, fusion).execute(
225
229
  "missing",
226
- { path: "missing.txt", content: "mutation\n", then_run: { command: "remove" } },
230
+ {
231
+ path: "missing.txt",
232
+ content: "mutation\n",
233
+ mode: "create",
234
+ then_run: { command: "remove" },
235
+ },
227
236
  undefined,
228
237
  undefined,
229
238
  context(dir),
@@ -244,7 +253,7 @@ test("write preserves command failure and changed freshness", async () =>
244
253
  });
245
254
  const result = await makeWriteOverride(dir, fusion).execute(
246
255
  "failed",
247
- { path: "failed.txt", content: "mutation\n", then_run: { command: "fail" } },
256
+ { path: "failed.txt", content: "mutation\n", mode: "create", then_run: { command: "fail" } },
248
257
  undefined,
249
258
  undefined,
250
259
  context(dir),
@@ -263,7 +272,7 @@ test("write rejects NUL content", async () =>
263
272
  await assert.rejects(
264
273
  write.execute(
265
274
  "nul",
266
- { path: "nul.txt", content: "a\0b" },
275
+ { path: "nul.txt", content: "a\0b", mode: "create" },
267
276
  undefined,
268
277
  undefined,
269
278
  context(dir),