@criogaid/pi-hashline-edit 0.5.1 → 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 (51) 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 +103 -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/failure-context.test.ts +4 -3
  22. package/src/pi/failure-path.test.ts +3 -3
  23. package/src/pi/file-commit.test.ts +24 -17
  24. package/src/pi/file-commit.ts +36 -9
  25. package/src/pi/file-snapshot.test.ts +24 -0
  26. package/src/pi/forget-tool.ts +268 -0
  27. package/src/pi/forget.test.ts +343 -0
  28. package/src/pi/forget.testing.ts +273 -0
  29. package/src/pi/grep-output.ts +57 -28
  30. package/src/pi/grep-search.ts +35 -12
  31. package/src/pi/grep-tool.ts +28 -9
  32. package/src/pi/grep.test.ts +173 -152
  33. package/src/pi/mutation-result.test.ts +23 -0
  34. package/src/pi/mutation-runner.ts +8 -4
  35. package/src/pi/path.ts +16 -2
  36. package/src/pi/pi.test.ts +3 -2
  37. package/src/pi/read-tool.ts +58 -26
  38. package/src/pi/read.test.ts +361 -0
  39. package/src/pi/registration.test.ts +115 -2
  40. package/src/pi/render.test.ts +45 -14
  41. package/src/pi/replace-tool.ts +18 -27
  42. package/src/pi/replace.test.ts +8 -107
  43. package/src/pi/result-safety.test.ts +123 -149
  44. package/src/pi/rg-match-bytes.ts +95 -0
  45. package/src/pi/rg-process.test.ts +40 -59
  46. package/src/pi/rg-text-view.ts +52 -5
  47. package/src/pi/tool-call.testing.ts +50 -0
  48. package/src/pi/tool-prompts.ts +15 -0
  49. package/src/pi/write-tool.ts +17 -26
  50. package/src/pi/write.test.ts +70 -61
  51. package/src/pi/e2e-scenarios.test.ts +0 -361
@@ -66,23 +66,53 @@ test("mutation headers refresh in place and retain isolated per-call counts", ()
66
66
  }
67
67
  });
68
68
 
69
- test("edit call titles show structured batches and tolerate invalid partial input", () => {
69
+ test("edit call titles count each operation type and refresh with partial input", () => {
70
70
  initTheme("dark");
71
71
  const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
72
72
  const edits = [
73
- { op: "replace" as const, anchor: "1#AB", body: ["new"] },
74
- { op: "append" as const, body: ["more"] },
73
+ { op: "replace", anchor: "1#AB", body: ["new"] },
74
+ { op: "append", body: ["more"] },
75
+ { op: "replace", anchor: "3#CD", body: ["changed"] },
76
+ { op: "delete", anchor: "5#EF" },
77
+ { op: "insert_before", anchor: "7#GH", body: ["before"] },
78
+ { op: "insert_after", anchor: "9#JK", body: ["after"] },
79
+ { op: "prepend", body: ["first"] },
75
80
  ];
76
- const render = (value: unknown) =>
77
- tool
78
- .renderCall({ path: "f.txt", edits: value } as Parameters<typeof tool.renderCall>[0], theme, {
79
- state: {},
80
- } as Parameters<typeof tool.renderCall>[2])
81
- .render(120)
82
- .join("\n");
83
- assert.match(render(edits), /2 ops: replace/);
84
- assert.doesNotMatch(render(JSON.stringify(edits)), /ops:/);
85
- assert.doesNotMatch(render("[{bad"), /ops:/);
81
+ let header: ReturnType<typeof tool.renderCall> | undefined;
82
+ const context = { state: {} } as Parameters<typeof tool.renderCall>[2];
83
+ const render = (value: unknown) => {
84
+ header = tool.renderCall(
85
+ // Streaming arguments reach the renderer before schema validation.
86
+ { path: "f.txt", edits: value } as Parameters<typeof tool.renderCall>[0],
87
+ theme,
88
+ { ...context, lastComponent: header },
89
+ );
90
+ return header.render(240).join("\n");
91
+ };
92
+ assert.match(render([edits[0], {}]), /unknown ×1/);
93
+ const mixed = render(edits);
94
+ assert.match(mixed, /7 ops:/);
95
+ for (const [kind, count] of [
96
+ ["replace", 2],
97
+ ["delete", 1],
98
+ ["insert_before", 1],
99
+ ["insert_after", 1],
100
+ ["append", 1],
101
+ ["prepend", 1],
102
+ ]) {
103
+ assert.ok(mixed.includes(`${kind} ×${count}`), mixed);
104
+ }
105
+ assert.doesNotMatch(mixed, /unknown/);
106
+ const single = render([edits[0]]);
107
+ assert.match(single, /1 op: replace ×1/);
108
+ assert.doesNotMatch(single, /append|delete|insert_before|insert_after|prepend/);
109
+ assert.match(
110
+ render([null, { op: "rep" }, { op: "__proto__" }, { op: { toString: null } }]),
111
+ /4 ops: unknown ×4/,
112
+ );
113
+ for (const invalid of [[], undefined, JSON.stringify(edits), "[{bad"]) {
114
+ assert.doesNotMatch(render(invalid), /ops?:/);
115
+ }
86
116
  });
87
117
 
88
118
  test("mutation card owns stale-anchor notices without internal status", () => {
@@ -159,7 +189,7 @@ test("mutation card omits status when then_run was not requested", () => {
159
189
  test("unfused write errors retain the native full diagnostic", () => {
160
190
  initTheme("dark");
161
191
  const tool = withMutationStatus(makeWriteOverride(process.cwd()));
162
- const args = { path: "a.txt", content: "new" };
192
+ const args = { path: "a.txt", content: "new", mode: "overwrite" as const };
163
193
  const context: any = { args, state: {}, isPartial: false, isError: true, invalidate() {} };
164
194
  const card = tool.renderCall!(args, theme, context);
165
195
  tool.renderResult!(
@@ -312,6 +342,7 @@ test("all file tools expose validation causes in collapsed and expanded error ca
312
342
  const args = {
313
343
  path: "unused.txt",
314
344
  content: "unused",
345
+ mode: "create" as const,
315
346
  edits: [{ op: "append" as const, body: ["unused"] }],
316
347
  replacements: [{ find: "unused", replace: "unused" }],
317
348
  unexpected: true,
@@ -24,7 +24,7 @@
24
24
  */
25
25
 
26
26
  import {
27
- type ExtensionContext,
27
+ type ExtensionToolContext,
28
28
  type Theme,
29
29
  type ToolDefinition,
30
30
  type ToolRenderResultOptions,
@@ -52,8 +52,14 @@ import {
52
52
  type MutationTarget,
53
53
  type TextMutationDetails,
54
54
  } from "./mutation-runner.ts";
55
+ import { MUTATION_TOOL_GUIDELINE } from "./tool-prompts.ts";
55
56
  import { errorMessage } from "../core/errors.ts";
56
- import { invalidArgument, throwIfCancelled } from "./error-text.ts";
57
+ import { throwIfCancelled } from "./error-text.ts";
58
+ import {
59
+ argumentItems,
60
+ createArgumentPreparer,
61
+ type ReportArgumentIssue,
62
+ } from "./argument-validation.ts";
57
63
  type ReplaceDetails = TextMutationDetails;
58
64
  type ReplaceRenderContext = Parameters<
59
65
  NonNullable<ToolDefinition<typeof replaceSchema>["renderCall"]>
@@ -66,7 +72,7 @@ const replacementSchema = Type.Object(
66
72
  find: Type.String({
67
73
  minLength: 1,
68
74
  description:
69
- "Text, or a JavaScript regex when regex is true (not grep's ripgrep syntax). CRLF in the file reads as LF, so a line break is \\n; in literal mode a backslash followed by n matches those two characters. In regex mode, ^ and $ need the m flag to match per line; \\d, \\w, and \\b are ASCII-based.",
75
+ "Text, or a JavaScript regex when regex is true. CRLF in the file reads as LF, so a line break is \\n; in literal mode a backslash followed by n matches those two characters. In regex mode, ^ and $ need the m flag to match per line; \\d, \\w, and \\b are ASCII-based.",
70
76
  }),
71
77
  replace: Type.String({
72
78
  description:
@@ -100,11 +106,7 @@ const replaceSchema = Type.Object(
100
106
  );
101
107
 
102
108
  function createReplaceSchema(actionFusion: boolean) {
103
- return withThenRunSchema(
104
- replaceSchema,
105
- "Command to run once after all replacements succeed; failure does not roll back the replacement.",
106
- actionFusion,
107
- );
109
+ return withThenRunSchema(replaceSchema, "replace", actionFusion);
108
110
  }
109
111
  type ReplaceParams = Static<typeof replaceSchema> & { then_run?: ThenRunInput };
110
112
 
@@ -169,19 +171,14 @@ function replaceHeader(args: ReplaceParams, theme: Theme, counts?: DiffCounts):
169
171
  return t;
170
172
  }
171
173
 
172
- /**
173
- * Checks the schema cannot express, run before Pi's schema validation: replacement
174
- * text must be writable as UTF-8, and regex rules must compile. Rules with malformed
175
- * fields are left to the schema. Arguments are never changed.
176
- */
177
- function checkReplaceArguments(args: unknown): void {
178
- const rules = (args as { replacements?: unknown } | null)?.replacements;
179
- if (!Array.isArray(rules)) return;
174
+ /** Report unwritable replacement text and regex compile errors; Pi checks field shapes. */
175
+ function checkReplaceArguments(args: unknown, report: ReportArgumentIssue): void {
176
+ const rules = argumentItems((args as { replacements?: unknown } | null)?.replacements);
180
177
  const validFlags = new RegExp(REGEX_FLAGS_PATTERN);
181
178
  rules.forEach((rule, index) => {
182
179
  const { find, replace, regex, flags } = (rule ?? {}) as Record<string, unknown>;
183
180
  const reason = typeof replace === "string" ? unwritableTextReason(replace) : undefined;
184
- if (reason) throw invalidArgument(`replacements[${index}].replace`, reason);
181
+ if (reason) report(`replacements[${index}].replace`, reason);
185
182
  if (
186
183
  regex === true &&
187
184
  typeof find === "string" &&
@@ -191,7 +188,7 @@ function checkReplaceArguments(args: unknown): void {
191
188
  try {
192
189
  buildRegex(find, true, flags);
193
190
  } catch (error) {
194
- throw invalidArgument(`replacements[${index}].find`, errorMessage(error));
191
+ report(`replacements[${index}].find`, errorMessage(error));
195
192
  }
196
193
  }
197
194
  });
@@ -209,15 +206,9 @@ export function makeReplaceTool(
209
206
  description:
210
207
  "Replace every match of one or more literal or JavaScript-regex rules in a file. Overlapping matches or a rule with no match reject the whole call. Returns a diff and fresh anchors.",
211
208
  promptSnippet: "Replace matching text across a file",
212
- promptGuidelines: [
213
- "Use replace for repeated literal or regex substitutions, or short changes inside long lines; use edit for line or block changes, insertions, and deletions.",
214
- ...(fusion ? ACTION_FUSION_GUIDELINES : []),
215
- ],
209
+ promptGuidelines: [MUTATION_TOOL_GUIDELINE, ...(fusion ? ACTION_FUSION_GUIDELINES : [])],
216
210
  parameters,
217
- prepareArguments(args: unknown): ReplaceParams {
218
- checkReplaceArguments(args);
219
- return args as ReplaceParams;
220
- },
211
+ prepareArguments: createArgumentPreparer("replace", parameters, checkReplaceArguments),
221
212
  renderShell: "default" as const,
222
213
 
223
214
  renderCall(args: ReplaceParams, theme: Theme, context: ReplaceRenderContext) {
@@ -246,7 +237,7 @@ export function makeReplaceTool(
246
237
  params: ReplaceParams & { then_run?: ThenRunInput },
247
238
  signal: AbortSignal | undefined,
248
239
  onUpdate: AgentToolUpdateCallback<ReplaceDetails> | undefined,
249
- ctx: ExtensionContext,
240
+ ctx: ExtensionToolContext,
250
241
  ) {
251
242
  return executeMutation<Omit<ReplaceParams, "then_run">, ReplaceDetails>(
252
243
  {
@@ -17,7 +17,6 @@ import { makeEditOverride } from "./edit-tool.ts";
17
17
  import { validateToolArguments } from "@earendil-works/pi-ai";
18
18
  import { callTool } from "./tool-call.testing.ts";
19
19
  import { createActionFusionExecutor } from "./action-fusion.ts";
20
- import { generateMutationDetails } from "./mutation-result.ts";
21
20
  import { DEFAULT_CONFIG } from "./config.ts";
22
21
 
23
22
  async function withDir<T>(fn: (dir: string) => Promise<T>): Promise<T> {
@@ -44,20 +43,6 @@ const stubTheme = { fg: (_k: string, s: string) => s, bold: (s: string) => s } a
44
43
  // singleton — initialize it once for this test process (watcher off by default).
45
44
  initTheme();
46
45
 
47
- test("replace find guidance distinguishes literal escapes and regex line anchors", () => {
48
- const tool = makeReplaceTool(process.cwd(), DEFAULT_CONFIG);
49
- const description: unknown = Reflect.get(
50
- tool.parameters.properties.replacements.items.properties.find,
51
- "description",
52
- );
53
- assert.ok(typeof description === "string");
54
- assert.match(description, /JavaScript regex/);
55
- assert.match(description, /not grep's ripgrep syntax/);
56
- assert.match(description, /CRLF.*LF.*\\n/);
57
- assert.match(description, /literal mode.*backslash followed by n.*two characters/);
58
- assert.match(description, /regex mode.*\^ and \$.*m flag.*per line/);
59
- });
60
-
61
46
  test("replace schema requires a non-empty replacements array", async () => {
62
47
  for (const fusion of [undefined, createActionFusionExecutor()]) {
63
48
  const tool = makeReplaceTool(process.cwd(), DEFAULT_CONFIG, fusion);
@@ -524,95 +509,6 @@ test("replace: multiline replacement (changes line count) still reports a correc
524
509
  });
525
510
  });
526
511
 
527
- test("replace renderResult: renders the diff without throwing", async () => {
528
- await withDir(async (dir) => {
529
- const f = join(dir, "f.txt");
530
- await writeFile(f, "a\nb\nc\n");
531
- const tool = makeReplaceTool(dir, DEFAULT_CONFIG);
532
- const r: any = await call(tool, { path: "f.txt", replacements: [{ find: "b", replace: "B" }] });
533
- const comp = tool.renderResult(
534
- { content: r.content, details: r.details },
535
- { isPartial: false, expanded: true },
536
- stubTheme,
537
- {
538
- args: { path: "f.txt", replacements: [{ find: "b", replace: "B" }] },
539
- isError: r.isError ?? false,
540
- state: {},
541
- invalidate: () => {},
542
- } as Parameters<typeof tool.renderResult>[3],
543
- );
544
- assert.match(comp.render(80).join("\n"), /B/, "rendered diff should contain the new content");
545
- });
546
- });
547
-
548
- test("replace renderResult: renders the error line without throwing", async () => {
549
- await withDir(async (dir) => {
550
- const f = join(dir, "f.txt");
551
- await writeFile(f, "a\n");
552
- const tool = makeReplaceTool(dir, DEFAULT_CONFIG);
553
- let thrown: any;
554
- const r: any = await call(tool, {
555
- path: "f.txt",
556
- replacements: [{ find: "zzz", replace: "y" }],
557
- }).catch((e: any) => {
558
- thrown = e;
559
- return null;
560
- });
561
- assert.ok(thrown, "expected the call to throw");
562
- const comp = tool.renderResult(
563
- {
564
- content: [{ type: "text", text: thrown.message }],
565
- details: generateMutationDetails(
566
- "f.txt",
567
- "a\n",
568
- "a\n",
569
- { publishedRevision: "r", observedRevision: "r" },
570
- "PUBLISHED",
571
- ),
572
- },
573
- { isPartial: false, expanded: false },
574
- stubTheme,
575
- {
576
- args: { path: "f.txt", replacements: [{ find: "zzz", replace: "y" }] },
577
- isError: true,
578
- } as Parameters<typeof tool.renderResult>[3],
579
- );
580
- assert.match(comp.render(80).join("\n"), /zero matches|no matches|match/i);
581
- });
582
- });
583
-
584
- test("replace header: renderResult refreshes the call header in place — no invalidate", async () => {
585
- await withDir(async (dir) => {
586
- const f = join(dir, "f.txt");
587
- await writeFile(f, "a\nb\nc\n");
588
- const tool = makeReplaceTool(dir, DEFAULT_CONFIG);
589
- const args = { path: "f.txt", replacements: [{ find: "b", replace: "B1\nB2" }] };
590
- const r: any = await call(tool, args);
591
- let invalidated = false;
592
- const context: any = {
593
- args,
594
- isError: false,
595
- state: {},
596
- invalidate: () => {
597
- invalidated = true;
598
- },
599
- };
600
- const header: any = tool.renderCall(args, stubTheme, context);
601
- assert.match(header.text, /1 rule\b/);
602
- assert.ok(!header.text.includes("+2"), "pre-execution header must not show counts");
603
- tool.renderResult(
604
- { content: r.content, details: r.details },
605
- { isPartial: false, expanded: true },
606
- stubTheme,
607
- context,
608
- );
609
- assert.deepEqual(context.state.diffCounts, { added: 2, removed: 1 });
610
- assert.ok(header.text.includes("+2"), "header should show added count");
611
- assert.ok(header.text.includes("-1"), "header should show removed count");
612
- assert.ok(!invalidated, "renderResult must not call invalidate");
613
- });
614
- });
615
-
616
512
  test("replace header retains the rule count when a long path wraps", () => {
617
513
  const tool = makeReplaceTool(process.cwd(), DEFAULT_CONFIG);
618
514
  const args = {
@@ -662,7 +558,7 @@ test("invalid batches reject every change and never run a fused command", async
662
558
  DEFAULT_CONFIG,
663
559
  createActionFusionExecutor(async () => {
664
560
  commands++;
665
- return "done";
561
+ return { status: "succeeded", output: "done" };
666
562
  }),
667
563
  );
668
564
  const first = { find: "bar", replace: "changed" };
@@ -807,10 +703,11 @@ test("successful batches run one command against the complete result", async ()
807
703
  const tool = makeReplaceTool(
808
704
  dir,
809
705
  DEFAULT_CONFIG,
810
- createActionFusionExecutor(async () => {
706
+ createActionFusionExecutor(async (_toolCallId, input) => {
707
+ assert.equal(input.command, "check");
811
708
  commands++;
812
709
  assert.equal(await readFile(file, "utf8"), "bar baz");
813
- return "checked";
710
+ return { status: "succeeded", output: "checked" };
814
711
  }),
815
712
  );
816
713
  const result = await tool.execute(
@@ -830,6 +727,10 @@ test("successful batches run one command against the complete result", async ()
830
727
  assert.equal(commands, 1);
831
728
  assert.ok(result.details.actionFusion);
832
729
  assert.equal(result.details.actionFusion.command, "succeeded");
730
+ assert.equal(result.details.actionFusion.freshness, "unchanged");
731
+ const command = result.content[1];
732
+ assert.ok(command.type === "text");
733
+ assert.match(command.text, /checked/);
833
734
  assert.ok(result.content[0].type === "text");
834
735
  assert.match(result.content[0].text, /Updated anchors/);
835
736
  }));