@criogaid/pi-hashline-edit 0.4.0 → 0.5.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 (66) hide show
  1. package/README.md +134 -30
  2. package/package.json +3 -3
  3. package/src/core/apply.test.ts +194 -104
  4. package/src/core/apply.ts +6 -37
  5. package/src/core/errors.ts +9 -0
  6. package/src/core/hash.test.ts +8 -8
  7. package/src/core/hash.ts +5 -5
  8. package/src/{pi/replace-apply.ts → core/replace.ts} +4 -4
  9. package/src/core/text.test.ts +30 -1
  10. package/src/core/text.ts +9 -6
  11. package/src/core/types.ts +4 -7
  12. package/src/index.ts +9 -11
  13. package/src/integration/config-registration.test.ts +206 -0
  14. package/src/integration/grep-rg.test.ts +285 -153
  15. package/src/integration/large-text.test.ts +11 -12
  16. package/src/integration/replace-package.test.ts +11 -7
  17. package/src/pi/action-fusion.test.ts +251 -39
  18. package/src/pi/action-fusion.ts +113 -117
  19. package/src/pi/anchor-format.test.ts +91 -24
  20. package/src/pi/anchor-format.ts +43 -9
  21. package/src/pi/budgets.ts +7 -2
  22. package/src/pi/config.test.ts +153 -40
  23. package/src/pi/config.ts +87 -41
  24. package/src/pi/diagnostic-buffer.test.ts +58 -0
  25. package/src/pi/diagnostic-buffer.ts +59 -0
  26. package/src/pi/e2e-scenarios.test.ts +13 -11
  27. package/src/pi/edit-tool.ts +21 -157
  28. package/src/pi/error-text.ts +10 -5
  29. package/src/pi/execute.test.ts +299 -175
  30. package/src/pi/failure-context.test.ts +7 -2
  31. package/src/pi/failure-context.ts +155 -8
  32. package/src/pi/failure-path.test.ts +33 -26
  33. package/src/pi/file-commit.ts +2 -1
  34. package/src/pi/fusion-card.test.ts +26 -0
  35. package/src/pi/fusion-card.ts +102 -6
  36. package/src/pi/grep-output.ts +50 -35
  37. package/src/pi/grep-render.ts +13 -15
  38. package/src/pi/grep-scope.ts +8 -46
  39. package/src/pi/grep-search.ts +90 -63
  40. package/src/pi/grep-tool.ts +109 -121
  41. package/src/pi/grep.test.ts +597 -377
  42. package/src/pi/mutation-outcome.testing.ts +22 -0
  43. package/src/pi/mutation-result.test.ts +51 -2
  44. package/src/pi/mutation-result.ts +62 -55
  45. package/src/pi/mutation-runner.ts +16 -33
  46. package/src/pi/pi.test.ts +11 -6
  47. package/src/pi/read-tool.ts +62 -34
  48. package/src/pi/registration.test.ts +7 -7
  49. package/src/pi/render.test.ts +143 -9
  50. package/src/pi/render.ts +32 -96
  51. package/src/pi/replace-regex.ts +54 -0
  52. package/src/pi/replace-tool.ts +25 -59
  53. package/src/pi/replace-worker.ts +2 -2
  54. package/src/pi/replace.test.ts +62 -58
  55. package/src/pi/result-safety.test.ts +124 -84
  56. package/src/pi/rg-line-ranges.ts +3 -2
  57. package/src/pi/{rg-line-filter.test.ts → rg-process.test.ts} +1 -1
  58. package/src/pi/{rg-line-filter.ts → rg-process.ts} +43 -9
  59. package/src/pi/rg-text-view.ts +25 -38
  60. package/src/pi/schema.ts +2 -10
  61. package/src/pi/text-stream.test.ts +153 -0
  62. package/src/pi/text-stream.ts +33 -13
  63. package/src/pi/write-tool.ts +3 -2
  64. package/src/pi/write.test.ts +10 -9
  65. package/src/core/index.ts +0 -14
  66. package/src/pi/state.ts +0 -26
@@ -1,8 +1,9 @@
1
1
  /**
2
- * Override grep: anchored `LINE#HASH│` results feed edit without a re-read.
3
- * Scope and paths live in grep-scope; ripgrep events in grep-search; output and
4
- * byte budgets in grep-output; TUI presentation in grep-render. This module
5
- * owns the tool schema, render wiring, and execution order.
2
+ * Override grep: valid UTF-8 results feed edit; malformed UTF-8 uses non-editable previews.
3
+ * Scope and paths live in grep-scope; search requests and ripgrep events in
4
+ * grep-search; the rg process layer in rg-process; result formatting in
5
+ * grep-output; TUI presentation in grep-render. This module owns the tool
6
+ * schema, the production backend, render wiring, and execution order.
6
7
  * @module pi-hashline-edit/pi
7
8
  */
8
9
 
@@ -10,108 +11,124 @@ import { type ToolDefinition } from "@earendil-works/pi-coding-agent";
10
11
  import { rgPath as bundledRgPath } from "@vscode/ripgrep";
11
12
  import { Type, type Static } from "typebox";
12
13
  import { Text } from "@earendil-works/pi-tui";
14
+ import { renderOutputPreview, renderToolError } from "./render.ts";
13
15
  import { normalizeLineEndings } from "../core/lines.ts";
14
16
  import { createAnchorFormatter } from "./anchor-format.ts";
15
- import { renderToolError } from "./render.ts";
16
17
  import { assembleGrepOutput, formatMatches, formatSearchWarnings } from "./grep-output.ts";
17
18
  import {
19
+ assertValidRegex,
18
20
  filterExplicitFilesByGlob,
19
- literalFallbackNotice as formatLiteralFallbackNotice,
20
- REGEX_SYNTAX,
21
- resolveLiteralMode,
22
21
  toArray,
23
22
  resolveSearchPaths,
24
23
  } from "./grep-scope.ts";
25
- import { searchMatches, type GrepBackend, type SearchScope } from "./grep-search.ts";
24
+ import {
25
+ searchMatches,
26
+ type GrepBackend,
27
+ type SearchScope,
28
+ type SearchFileSnapshot,
29
+ } from "./grep-search.ts";
26
30
  export type { GrepBackend } from "./grep-search.ts";
27
31
  import { toDisplayLines } from "./grep-render.ts";
28
- import { resolveIgnoreCase, runRg, runRgPaths, type SearchModes } from "./rg-line-filter.ts";
32
+ import { probeRegex, resolveIgnoreCase, runRgPaths, type SearchModes } from "./rg-process.ts";
29
33
  import { runRgTextView } from "./rg-text-view.ts";
30
- import { integerRange, POSITIVE_SAFE_INTEGER } from "./schema.ts";
34
+ import { GREP_CONTEXT_RANGE, POSITIVE_SAFE_INTEGER } from "./schema.ts";
31
35
  import { throwIfCancelled } from "./error-text.ts";
36
+ import type { HashlineEditConfig } from "./config.ts";
32
37
 
33
- const DEFAULT_LIMIT = 100;
34
- const GREP_CONTEXT_MAX = 20;
35
-
36
- const grepOverrideSchema = Type.Object(
37
- {
38
- pattern: Type.Union(
39
- [Type.String({ minLength: 1 }), Type.Array(Type.String({ minLength: 1 }), { minItems: 1 })],
40
- {
41
- description:
42
- "String or array of strings (an array matches any of them). Regex syntax is ripgrep's Rust regex, not JavaScript: no lookaround or backreferences; ^ and $ match at line boundaries.",
43
- },
44
- ),
45
- path: Type.Optional(
46
- Type.Union(
38
+ /** Grep parameters; descriptions state the configured defaults. */
39
+ function createGrepSchema({ defaultLimit, defaultContext }: HashlineEditConfig["grep"]) {
40
+ return Type.Object(
41
+ {
42
+ pattern: Type.Union(
47
43
  [Type.String({ minLength: 1 }), Type.Array(Type.String({ minLength: 1 }), { minItems: 1 })],
48
44
  {
49
45
  description:
50
- "Existing file or directory, or an array of them; omit to search the working directory. Wildcards are not expanded; use glob.",
46
+ "String or array of strings (an array matches any of them). Regex syntax is ripgrep's Rust regex, not JavaScript: no lookaround or backreferences; ^ and $ match at line boundaries.",
51
47
  },
52
48
  ),
53
- ),
54
- glob: Type.Optional(
55
- Type.Union(
56
- [Type.String({ minLength: 1 }), Type.Array(Type.String({ minLength: 1 }), { minItems: 1 })],
57
- {
58
- description:
59
- "Filename glob, or an ordered array of them; prefix exclusions with !, e.g. ['*.ts', '!**/*.test.ts'].",
60
- },
49
+ path: Type.Optional(
50
+ Type.Union(
51
+ [
52
+ Type.String({ minLength: 1 }),
53
+ Type.Array(Type.String({ minLength: 1 }), { minItems: 1 }),
54
+ ],
55
+ {
56
+ description:
57
+ "Existing file or directory, or an array of them; omit to search the working directory. Wildcards are not expanded; use glob.",
58
+ },
59
+ ),
61
60
  ),
62
- ),
63
- literal: Type.Optional(
64
- Type.Boolean({
65
- description:
66
- "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.",
67
- }),
68
- ),
69
- ignoreCase: Type.Optional(
70
- Type.Boolean({
71
- description:
72
- "true ignores case, false matches case; omitted uses smart-case for the whole query. Inline regex flags still apply.",
73
- }),
74
- ),
75
- multiline: Type.Optional(
76
- Type.Boolean({
77
- description:
78
- "Match across lines (default false); every line a match touches is anchored. The . wildcard does not match newlines; use \\n or (?s).",
79
- }),
80
- ),
81
- context: Type.Optional(
82
- Type.Number({
83
- ...integerRange(0, GREP_CONTEXT_MAX),
84
- description: `Anchored lines shown before and after each match (0-${GREP_CONTEXT_MAX}, default 0); display only, not matched.`,
85
- }),
86
- ),
87
- limit: Type.Optional(
88
- Type.Number({
89
- ...POSITIVE_SAFE_INTEGER,
90
- description: "Maximum matching lines, across all files (default 100).",
91
- }),
92
- ),
93
- outputMode: Type.Optional(
94
- Type.Union([Type.Literal("content"), Type.Literal("files"), Type.Literal("count")], {
61
+ glob: Type.Optional(
62
+ Type.Union(
63
+ [
64
+ Type.String({ minLength: 1 }),
65
+ Type.Array(Type.String({ minLength: 1 }), { minItems: 1 }),
66
+ ],
67
+ {
68
+ description:
69
+ "Filename glob, or an ordered array of them; prefix exclusions with !, e.g. ['*.ts', '!**/*.test.ts'].",
70
+ },
71
+ ),
72
+ ),
73
+ literal: Type.Boolean({
95
74
  description:
96
- '"content" (default): anchored lines; "files": paths; "count": matching lines per file and total. All modes share limit.',
75
+ "true: match the text exactly, including regex punctuation. false: ripgrep Rust regex, where foo(0) matches foo0.",
97
76
  }),
98
- ),
99
- },
100
- { additionalProperties: false },
101
- );
102
- type GrepTool = ToolDefinition<typeof grepOverrideSchema, { incomplete?: true } | undefined>;
77
+ ignoreCase: Type.Optional(
78
+ Type.Boolean({
79
+ description:
80
+ "true ignores case, false matches case; omitted uses smart-case for the whole query. Inline regex flags still apply.",
81
+ }),
82
+ ),
83
+ multiline: Type.Optional(
84
+ Type.Boolean({
85
+ description:
86
+ "Match across lines (default false); content mode returns every line a match touches. The . wildcard does not match newlines; use \\n or (?s).",
87
+ }),
88
+ ),
89
+ context: Type.Optional(
90
+ Type.Number({
91
+ ...GREP_CONTEXT_RANGE,
92
+ description: `Lines shown before and after each match (${GREP_CONTEXT_RANGE.minimum}-${GREP_CONTEXT_RANGE.maximum}, default ${defaultContext}); display only, not matched.`,
93
+ }),
94
+ ),
95
+ limit: Type.Optional(
96
+ Type.Number({
97
+ ...POSITIVE_SAFE_INTEGER,
98
+ description: `Maximum matching lines, across all files (default ${defaultLimit}).`,
99
+ }),
100
+ ),
101
+ outputMode: Type.Optional(
102
+ Type.Union([Type.Literal("content"), Type.Literal("files"), Type.Literal("count")], {
103
+ description:
104
+ '"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.',
105
+ }),
106
+ ),
107
+ },
108
+ { additionalProperties: false },
109
+ );
110
+ }
111
+ type GrepSchema = ReturnType<typeof createGrepSchema>;
112
+ type GrepTool = ToolDefinition<GrepSchema, { incomplete?: true } | undefined>;
103
113
 
104
114
  /** Build the production grep override (a ToolDefinition fragment for registerTool). */
105
- export function makeGrepOverride(cwd: string) {
106
- return makeGrepOverrideWithBackend(cwd, {});
115
+ export function makeGrepOverride(cwd: string, config: HashlineEditConfig) {
116
+ return makeGrepOverrideWithBackend(cwd, config, {});
107
117
  }
108
118
 
109
119
  /** @internal — build a grep override with deterministic process backends for tests. */
110
- export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<GrepBackend>) {
120
+ export function makeGrepOverrideWithBackend(
121
+ cwd: string,
122
+ config: HashlineEditConfig,
123
+ overrides: Partial<GrepBackend>,
124
+ ) {
125
+ const { hashLen } = config;
126
+ const grepSchema = createGrepSchema(config.grep);
111
127
  const backend: GrepBackend = {
112
- runRg: runRgTextView,
128
+ search: runRgTextView,
113
129
  runRgPaths,
114
130
  resolveIgnoreCase,
131
+ probeRegex,
115
132
  ...overrides,
116
133
  };
117
134
 
@@ -119,22 +136,22 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
119
136
  name: "grep" as const,
120
137
  label: "grep",
121
138
  description:
122
- "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.",
139
+ "Search file contents with ripgrep. Content mode returns LINE#HASH edit anchors for valid UTF-8; invalid UTF-8 uses replacement characters and plain line numbers. NUL-containing files are skipped. 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. Directory searches respect ignore rules and skip linked directories.",
123
140
  promptSnippet: "Search file contents with ripgrep",
124
141
  promptGuidelines: [
125
142
  "Prefer grep for file-content searches; use another tool for ignored or linked directories.",
126
143
  'In grep, omit path to search the working directory (never pass ""); use glob for filename wildcards.',
127
- "In grep, set literal:true for code with regex punctuation; grep regex is ripgrep (Rust) syntax without lookaround or backreferences.",
144
+ "In grep, use literal:true for exact text, including names, paths, and code snippets; use literal:false only for intentional ripgrep (Rust) regex, which has no lookaround or backreferences.",
128
145
  "In grep, use a pattern array for alternatives instead of joining them with |, and context:3-5 when searching code to edit.",
129
146
  "In grep, use multiline:true for cross-line matches and outputMode files or count when only paths or counts are needed.",
130
147
  "Copy grep anchors directly into edit; read the full line before rewriting from a partial preview.",
131
148
  ],
132
- parameters: grepOverrideSchema,
149
+ parameters: grepSchema,
133
150
 
134
151
  renderShell: "default" as const,
135
152
 
136
153
  renderCall(
137
- args: Static<typeof grepOverrideSchema>,
154
+ args: Static<GrepSchema>,
138
155
  theme: Parameters<NonNullable<GrepTool["renderCall"]>>[1],
139
156
  ) {
140
157
  const rawPattern = args?.pattern;
@@ -161,51 +178,30 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
161
178
  context: Parameters<NonNullable<GrepTool["renderResult"]>>[3],
162
179
  ) {
163
180
  if (isPartial) return new Text(theme.fg("warning", "Searching…"), 0, 0);
164
- if (context?.isError) return renderToolError(result, theme);
181
+ if (context?.isError) return renderToolError(result, theme, expanded);
165
182
  const out = result.content?.[0]?.type === "text" ? result.content[0].text : "";
166
- const styled = toDisplayLines(out, theme);
167
- const maxLines = expanded ? styled.length : 15;
168
- const shown = styled.slice(0, maxLines);
169
- const more =
170
- !expanded && styled.length > maxLines
171
- ? `\n${theme.fg("muted", `… (${styled.length - maxLines} more lines)`)}`
172
- : "";
173
- return new Text(shown.join("\n") + more, 0, 0);
183
+ return renderOutputPreview(toDisplayLines(out, theme), expanded, theme);
174
184
  },
175
185
 
176
186
  async execute(
177
187
  _toolCallId: string,
178
- params: Static<typeof grepOverrideSchema>,
188
+ params: Static<GrepSchema>,
179
189
  signal: AbortSignal | undefined,
180
190
  _onUpdate: Parameters<GrepTool["execute"]>[3],
181
191
  ) {
182
192
  throwIfCancelled(signal);
183
- const anchors = createAnchorFormatter();
193
+ const anchors = createAnchorFormatter(hashLen);
184
194
  const warnings: string[] = [];
185
195
 
186
196
  const patterns = toArray(params.pattern).map(normalizeLineEndings);
187
- const effectiveLimit = params.limit ?? DEFAULT_LIMIT;
188
- const context = params.context ?? 0;
197
+ const effectiveLimit = params.limit ?? config.grep.defaultLimit;
198
+ const context = params.context ?? config.grep.defaultContext;
189
199
  const rgPath = bundledRgPath;
190
200
  const outputMode: "content" | "files" | "count" = params.outputMode ?? "content";
191
201
  const multiline = params.multiline ?? false;
192
202
  const globs = toArray(params.glob);
193
- const literal = await resolveLiteralMode(
194
- patterns,
195
- params.literal,
196
- multiline,
197
- rgPath,
198
- backend,
199
- signal,
200
- patterns.length === 1,
201
- );
202
- const literalFallback =
203
- params.literal === undefined &&
204
- literal &&
205
- patterns.some((pattern) => REGEX_SYNTAX.test(pattern));
206
- const literalFallbackNotice = literalFallback
207
- ? formatLiteralFallbackNotice(patterns)
208
- : undefined;
203
+ const { literal } = params;
204
+ if (!literal) await assertValidRegex(patterns, multiline, rgPath, backend, signal);
209
205
  const matcherIgnoreCase = await backend.resolveIgnoreCase(
210
206
  rgPath,
211
207
  patterns,
@@ -237,7 +233,7 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
237
233
 
238
234
  const result =
239
235
  scope.searchPaths.length === 0
240
- ? { raw: [], matchLimitReached: false, revisions: new Map<string, string>() }
236
+ ? { raw: [], matchLimitReached: false, snapshots: new Map<string, SearchFileSnapshot>() }
241
237
  : await searchMatches({
242
238
  backend,
243
239
  rgPath,
@@ -255,14 +251,7 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
255
251
  if (warnings.length)
256
252
  throw new Error(`No matches confirmed.${formatSearchWarnings(warnings)}`);
257
253
  return {
258
- content: [
259
- {
260
- type: "text" as const,
261
- text:
262
- "No matches found" +
263
- (literalFallbackNotice ? `\n\n[${literalFallbackNotice}]` : ""),
264
- },
265
- ],
254
+ content: [{ type: "text" as const, text: "No matches found" }],
266
255
  details: undefined,
267
256
  };
268
257
  }
@@ -275,13 +264,12 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
275
264
  anchors,
276
265
  signal,
277
266
  warnings,
278
- searchRevisions: result.revisions,
267
+ searchSnapshots: result.snapshots,
279
268
  });
280
269
  return assembleGrepOutput({
281
270
  blocks,
282
271
  warnings,
283
272
  outputMode,
284
- literalFallbackNotice,
285
273
  matchLimitReached,
286
274
  effectiveLimit,
287
275
  linesTruncated,