@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
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Override grep: anchored `LINE#HASH│` results feed edit without a re-read.
2
+ * Override grep: valid UTF-8 results feed edit; malformed UTF-8 uses non-editable previews.
3
3
  * Scope and paths live in grep-scope; search requests and ripgrep events in
4
4
  * grep-search; the rg process layer in rg-process; result formatting in
5
5
  * grep-output; TUI presentation in grep-render. This module owns the tool
@@ -11,19 +11,23 @@ import { type ToolDefinition } from "@earendil-works/pi-coding-agent";
11
11
  import { rgPath as bundledRgPath } from "@vscode/ripgrep";
12
12
  import { Type, type Static } from "typebox";
13
13
  import { Text } from "@earendil-works/pi-tui";
14
+ import { renderOutputPreview, renderToolError } from "./render.ts";
15
+ import { type ForgetReceiptDetails, grepReceipt, withResultTag } from "./forget-tool.ts";
14
16
  import { normalizeLineEndings } from "../core/lines.ts";
15
17
  import { createAnchorFormatter } from "./anchor-format.ts";
16
- import { renderToolError } from "./render.ts";
17
18
  import { assembleGrepOutput, formatMatches, formatSearchWarnings } from "./grep-output.ts";
18
19
  import {
20
+ assertValidRegex,
19
21
  filterExplicitFilesByGlob,
20
- literalFallbackNotice as formatLiteralFallbackNotice,
21
- REGEX_SYNTAX,
22
- resolveLiteralMode,
23
22
  toArray,
24
23
  resolveSearchPaths,
25
24
  } from "./grep-scope.ts";
26
- import { searchMatches, type GrepBackend, type SearchScope } from "./grep-search.ts";
25
+ import {
26
+ searchMatches,
27
+ type GrepBackend,
28
+ type SearchScope,
29
+ type SearchFileSnapshot,
30
+ } from "./grep-search.ts";
27
31
  export type { GrepBackend } from "./grep-search.ts";
28
32
  import { toDisplayLines } from "./grep-render.ts";
29
33
  import { probeRegex, resolveIgnoreCase, runRgPaths, type SearchModes } from "./rg-process.ts";
@@ -31,6 +35,7 @@ import { runRgTextView } from "./rg-text-view.ts";
31
35
  import { GREP_CONTEXT_RANGE, POSITIVE_SAFE_INTEGER } from "./schema.ts";
32
36
  import { throwIfCancelled } from "./error-text.ts";
33
37
  import type { HashlineEditConfig } from "./config.ts";
38
+ import { createArgumentPreparer } from "./argument-validation.ts";
34
39
 
35
40
  /** Grep parameters; descriptions state the configured defaults. */
36
41
  function createGrepSchema({ defaultLimit, defaultContext }: HashlineEditConfig["grep"]) {
@@ -51,7 +56,7 @@ function createGrepSchema({ defaultLimit, defaultContext }: HashlineEditConfig["
51
56
  ],
52
57
  {
53
58
  description:
54
- "Existing file or directory, or an array of them; omit to search the working directory. Wildcards are not expanded; use glob.",
59
+ "Existing file or directory, or an array of them; omit to search the working directory. Wildcards are not expanded.",
55
60
  },
56
61
  ),
57
62
  ),
@@ -67,12 +72,10 @@ function createGrepSchema({ defaultLimit, defaultContext }: HashlineEditConfig["
67
72
  },
68
73
  ),
69
74
  ),
70
- literal: Type.Optional(
71
- Type.Boolean({
72
- description:
73
- "true: match the text literally. false: ripgrep Rust regex. Omitted: regex when the pattern has metacharacters; a single invalid pattern falls back to a literal search of the whole string, an invalid array fails.",
74
- }),
75
- ),
75
+ literal: Type.Boolean({
76
+ description:
77
+ "true: match the text exactly, including regex punctuation. false: ripgrep Rust regex, where foo(0) matches foo0.",
78
+ }),
76
79
  ignoreCase: Type.Optional(
77
80
  Type.Boolean({
78
81
  description:
@@ -82,13 +85,13 @@ function createGrepSchema({ defaultLimit, defaultContext }: HashlineEditConfig["
82
85
  multiline: Type.Optional(
83
86
  Type.Boolean({
84
87
  description:
85
- "Match across lines (default false); every line a match touches is anchored. The . wildcard does not match newlines; use \\n or (?s).",
88
+ "Match across lines (default false); content mode returns every line a match touches. The . wildcard does not match newlines; use \\n or (?s).",
86
89
  }),
87
90
  ),
88
91
  context: Type.Optional(
89
92
  Type.Number({
90
93
  ...GREP_CONTEXT_RANGE,
91
- description: `Anchored lines shown before and after each match (${GREP_CONTEXT_RANGE.minimum}-${GREP_CONTEXT_RANGE.maximum}, default ${defaultContext}); display only, not matched.`,
94
+ description: `Lines shown before and after each match (${GREP_CONTEXT_RANGE.minimum}-${GREP_CONTEXT_RANGE.maximum}, default ${defaultContext}); display only, not matched.`,
92
95
  }),
93
96
  ),
94
97
  limit: Type.Optional(
@@ -100,7 +103,7 @@ function createGrepSchema({ defaultLimit, defaultContext }: HashlineEditConfig["
100
103
  outputMode: Type.Optional(
101
104
  Type.Union([Type.Literal("content"), Type.Literal("files"), Type.Literal("count")], {
102
105
  description:
103
- '"content" (default): anchored lines; "files": paths; "count": matching lines per file and total. All modes share limit.',
106
+ '"content" (default): matches/context with anchors for valid UTF-8 or plain previews otherwise; "files": paths; "count": matching lines per file and total. All modes share limit.',
104
107
  }),
105
108
  ),
106
109
  },
@@ -108,7 +111,10 @@ function createGrepSchema({ defaultLimit, defaultContext }: HashlineEditConfig["
108
111
  );
109
112
  }
110
113
  type GrepSchema = ReturnType<typeof createGrepSchema>;
111
- type GrepTool = ToolDefinition<GrepSchema, { incomplete?: true } | undefined>;
114
+ type GrepTool = ToolDefinition<
115
+ GrepSchema,
116
+ ({ incomplete?: true } & ForgetReceiptDetails) | undefined
117
+ >;
112
118
 
113
119
  /** Build the production grep override (a ToolDefinition fragment for registerTool). */
114
120
  export function makeGrepOverride(cwd: string, config: HashlineEditConfig) {
@@ -135,17 +141,18 @@ export function makeGrepOverrideWithBackend(
135
141
  name: "grep" as const,
136
142
  label: "grep",
137
143
  description:
138
- "Search file contents with ripgrep. Content mode returns LINE#HASH anchors usable by edit; files/count modes return paths or matching-line counts. CRLF is searched as LF. Directory searches respect ignore rules and skip linked directories.",
144
+ "Search file contents with ripgrep. Content mode returns LINE#HASH edit anchors for valid UTF-8 and plain line numbers without anchors otherwise; files/count modes return paths or matching-line counts. Valid UTF-8 CRLF is searched as LF; invalid UTF-8 is searched as raw bytes. NUL-containing files are skipped. Directory searches respect ignore rules and skip linked directories.",
139
145
  promptSnippet: "Search file contents with ripgrep",
140
146
  promptGuidelines: [
141
147
  "Prefer grep for file-content searches; use another tool for ignored or linked directories.",
142
- 'In grep, omit path to search the working directory (never pass ""); use glob for filename wildcards.',
143
- "In grep, set literal:true for code with regex punctuation; grep regex is ripgrep (Rust) syntax without lookaround or backreferences.",
148
+ "In grep, use glob for filename wildcards.",
149
+ "In grep, use literal:true for exact text, including names, paths, and code snippets; use literal:false only for intentional regex.",
144
150
  "In grep, use a pattern array for alternatives instead of joining them with |, and context:3-5 when searching code to edit.",
145
151
  "In grep, use multiline:true for cross-line matches and outputMode files or count when only paths or counts are needed.",
146
152
  "Copy grep anchors directly into edit; read the full line before rewriting from a partial preview.",
147
153
  ],
148
154
  parameters: grepSchema,
155
+ prepareArguments: createArgumentPreparer("grep", grepSchema),
149
156
 
150
157
  renderShell: "default" as const,
151
158
 
@@ -177,20 +184,13 @@ export function makeGrepOverrideWithBackend(
177
184
  context: Parameters<NonNullable<GrepTool["renderResult"]>>[3],
178
185
  ) {
179
186
  if (isPartial) return new Text(theme.fg("warning", "Searching…"), 0, 0);
180
- if (context?.isError) return renderToolError(result, theme);
187
+ if (context?.isError) return renderToolError(result, theme, expanded);
181
188
  const out = result.content?.[0]?.type === "text" ? result.content[0].text : "";
182
- const styled = toDisplayLines(out, theme);
183
- const maxLines = expanded ? styled.length : 15;
184
- const shown = styled.slice(0, maxLines);
185
- const more =
186
- !expanded && styled.length > maxLines
187
- ? `\n${theme.fg("muted", `… (${styled.length - maxLines} more lines)`)}`
188
- : "";
189
- return new Text(shown.join("\n") + more, 0, 0);
189
+ return renderOutputPreview(toDisplayLines(out, theme), expanded, theme);
190
190
  },
191
191
 
192
192
  async execute(
193
- _toolCallId: string,
193
+ toolCallId: string,
194
194
  params: Static<GrepSchema>,
195
195
  signal: AbortSignal | undefined,
196
196
  _onUpdate: Parameters<GrepTool["execute"]>[3],
@@ -199,29 +199,20 @@ export function makeGrepOverrideWithBackend(
199
199
  const anchors = createAnchorFormatter(hashLen);
200
200
  const warnings: string[] = [];
201
201
 
202
- const patterns = toArray(params.pattern).map(normalizeLineEndings);
202
+ const patterns = toArray(params.pattern);
203
203
  const effectiveLimit = params.limit ?? config.grep.defaultLimit;
204
204
  const context = params.context ?? config.grep.defaultContext;
205
205
  const rgPath = bundledRgPath;
206
206
  const outputMode: "content" | "files" | "count" = params.outputMode ?? "content";
207
207
  const multiline = params.multiline ?? false;
208
208
  const globs = toArray(params.glob);
209
- const literal = await resolveLiteralMode(
210
- patterns,
211
- params.literal,
212
- multiline,
213
- rgPath,
214
- backend,
215
- signal,
216
- patterns.length === 1,
217
- );
218
- const literalFallback =
219
- params.literal === undefined &&
220
- literal &&
221
- patterns.some((pattern) => REGEX_SYNTAX.test(pattern));
222
- const literalFallbackNotice = literalFallback
223
- ? formatLiteralFallbackNotice(patterns)
224
- : undefined;
209
+ const { literal } = params;
210
+ if (!literal) {
211
+ await assertValidRegex(patterns, multiline, rgPath, backend, signal);
212
+ const normalized = patterns.map(normalizeLineEndings);
213
+ if (patterns.some((pattern, index) => pattern !== normalized[index]))
214
+ await assertValidRegex(normalized, multiline, rgPath, backend, signal);
215
+ }
225
216
  const matcherIgnoreCase = await backend.resolveIgnoreCase(
226
217
  rgPath,
227
218
  patterns,
@@ -253,7 +244,7 @@ export function makeGrepOverrideWithBackend(
253
244
 
254
245
  const result =
255
246
  scope.searchPaths.length === 0
256
- ? { raw: [], matchLimitReached: false, revisions: new Map<string, string>() }
247
+ ? { raw: [], matchLimitReached: false, snapshots: new Map<string, SearchFileSnapshot>() }
257
248
  : await searchMatches({
258
249
  backend,
259
250
  rgPath,
@@ -271,14 +262,7 @@ export function makeGrepOverrideWithBackend(
271
262
  if (warnings.length)
272
263
  throw new Error(`No matches confirmed.${formatSearchWarnings(warnings)}`);
273
264
  return {
274
- content: [
275
- {
276
- type: "text" as const,
277
- text:
278
- "No matches found" +
279
- (literalFallbackNotice ? `\n\n[${literalFallbackNotice}]` : ""),
280
- },
281
- ],
265
+ content: [{ type: "text" as const, text: "No matches found" }],
282
266
  details: undefined,
283
267
  };
284
268
  }
@@ -291,17 +275,24 @@ export function makeGrepOverrideWithBackend(
291
275
  anchors,
292
276
  signal,
293
277
  warnings,
294
- searchRevisions: result.revisions,
278
+ searchSnapshots: result.snapshots,
295
279
  });
296
- return assembleGrepOutput({
280
+ const output = assembleGrepOutput({
297
281
  blocks,
298
282
  warnings,
299
283
  outputMode,
300
- literalFallbackNotice,
301
284
  matchLimitReached,
302
285
  effectiveLimit,
303
286
  linesTruncated,
304
287
  });
288
+ // Only content mode returns file text; paths and counts have nothing to forget.
289
+ if (outputMode !== "content") return output;
290
+ return withResultTag(toolCallId, output, config.forget, () =>
291
+ grepReceipt(patterns, raw.length, new Set(raw.map((match) => match.filePath)).size, {
292
+ limitReached: matchLimitReached,
293
+ incomplete: warnings.length > 0,
294
+ }),
295
+ );
305
296
  },
306
297
  } satisfies GrepTool;
307
298
  }