@criogaid/pi-hashline-edit 0.6.1 → 0.7.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 (148) hide show
  1. package/README.md +161 -304
  2. package/THIRD_PARTY_NOTICES.md +80 -0
  3. package/package.json +10 -6
  4. package/src/core/AGENTS.md +20 -0
  5. package/src/core/apply.test.ts +189 -60
  6. package/src/core/apply.ts +110 -74
  7. package/src/core/case-fold.test.ts +40 -0
  8. package/src/core/case-fold.ts +81 -0
  9. package/src/core/character-set.test.ts +103 -0
  10. package/src/core/character-set.ts +170 -0
  11. package/src/core/errors.test.ts +23 -0
  12. package/src/core/errors.ts +70 -4
  13. package/src/core/lines.ts +7 -0
  14. package/src/core/regex.ts +21 -0
  15. package/src/core/replace-schema.ts +34 -0
  16. package/src/core/replace.ts +37 -54
  17. package/src/core/search-analysis.test.ts +199 -0
  18. package/src/core/search-analysis.ts +375 -0
  19. package/src/core/search-matrix.test.ts +64 -0
  20. package/src/core/search-matrix.testing.ts +183 -0
  21. package/src/core/search-schema.ts +18 -0
  22. package/src/core/search.test.ts +145 -0
  23. package/src/core/search.ts +119 -0
  24. package/src/core/text.test.ts +16 -8
  25. package/src/core/text.ts +26 -6
  26. package/src/core/types.ts +16 -11
  27. package/src/index.ts +25 -15
  28. package/src/integration/config-registration.test.ts +30 -24
  29. package/src/integration/forget-grep.test.ts +52 -2
  30. package/src/integration/fusion-dispatch.test.ts +21 -105
  31. package/src/integration/grep-errors.test.ts +50 -0
  32. package/src/integration/grep-flags.test.ts +280 -0
  33. package/src/integration/grep-js-completeness.test.ts +208 -0
  34. package/src/integration/grep-line-candidates.test.ts +233 -0
  35. package/src/integration/grep-matrix.test.ts +121 -0
  36. package/src/integration/grep-path-matrix.test.ts +132 -0
  37. package/src/integration/grep-prefilter-coverage.test.ts +189 -0
  38. package/src/integration/grep-regex.test.ts +410 -0
  39. package/src/integration/grep-rg.test.ts +220 -402
  40. package/src/integration/grep-scan-budget.test.ts +89 -0
  41. package/src/integration/grep-translation.test.ts +206 -0
  42. package/src/integration/large-text.test.ts +57 -1
  43. package/src/integration/model-budget-lifecycle.test.ts +128 -0
  44. package/src/integration/mutation-file-types.test.ts +12 -25
  45. package/src/integration/mutation-file-types.testing.ts +33 -0
  46. package/src/integration/npm-package.test.ts +17 -0
  47. package/src/integration/npm-package.testing.ts +123 -0
  48. package/src/integration/publication-read-changes.test.ts +344 -0
  49. package/src/integration/read-changes.test.ts +98 -0
  50. package/src/integration/replace-package.test.ts +17 -36
  51. package/src/integration/replace-package.testing.ts +33 -0
  52. package/src/integration/replace-worker-boundary.test.ts +107 -0
  53. package/src/integration/report-replay.test.ts +90 -0
  54. package/src/integration/utf8-errors.test.ts +46 -0
  55. package/src/pi/AGENTS.md +55 -0
  56. package/src/pi/action-fusion.test.ts +253 -103
  57. package/src/pi/action-fusion.ts +116 -290
  58. package/src/pi/anchor-format.ts +9 -0
  59. package/src/pi/argument-diagnostics.ts +478 -0
  60. package/src/pi/argument-error.testing.ts +43 -0
  61. package/src/pi/argument-error.ts +78 -0
  62. package/src/pi/argument-format.test.ts +208 -0
  63. package/src/pi/argument-validation.test.ts +742 -45
  64. package/src/pi/argument-validation.ts +55 -57
  65. package/src/pi/budgets.ts +45 -16
  66. package/src/pi/codemode.test.ts +96 -0
  67. package/src/pi/config.test.ts +14 -10
  68. package/src/pi/config.ts +21 -7
  69. package/src/pi/diagnostic-buffer.test.ts +52 -16
  70. package/src/pi/diagnostic-buffer.ts +11 -14
  71. package/src/pi/directory-sync.test.ts +4 -1
  72. package/src/pi/edit-tool.ts +100 -93
  73. package/src/pi/error-text.ts +39 -16
  74. package/src/pi/execute.test.ts +362 -315
  75. package/src/pi/extension-loading.test.ts +7 -27
  76. package/src/pi/extension-loading.testing.ts +2 -14
  77. package/src/pi/failure-context.test.ts +220 -88
  78. package/src/pi/failure-context.ts +161 -180
  79. package/src/pi/failure-path.test.ts +85 -88
  80. package/src/pi/file-commit.test.ts +78 -45
  81. package/src/pi/file-commit.ts +218 -151
  82. package/src/pi/file-read.test.ts +29 -0
  83. package/src/pi/file-read.ts +60 -0
  84. package/src/pi/file-snapshot.test.ts +1 -1
  85. package/src/pi/forget-tool.ts +189 -90
  86. package/src/pi/forget.test.ts +309 -22
  87. package/src/pi/forget.testing.ts +41 -113
  88. package/src/pi/fusion-card.test.ts +40 -14
  89. package/src/pi/fusion-card.ts +84 -50
  90. package/src/pi/grep-candidates.test.ts +127 -0
  91. package/src/pi/grep-candidates.ts +193 -0
  92. package/src/pi/grep-matrix.test.ts +83 -0
  93. package/src/pi/grep-output.ts +181 -138
  94. package/src/pi/grep-render.ts +28 -25
  95. package/src/pi/grep-scope.ts +61 -53
  96. package/src/pi/grep-search.ts +299 -242
  97. package/src/pi/grep-tool.ts +150 -140
  98. package/src/pi/grep-worker.mjs +4 -0
  99. package/src/pi/grep-worker.ts +14 -0
  100. package/src/pi/grep.test.ts +631 -632
  101. package/src/pi/model-budgets.test.ts +43 -0
  102. package/src/pi/model-budgets.ts +44 -0
  103. package/src/pi/mutation-outcome.testing.ts +5 -5
  104. package/src/pi/mutation-result.test.ts +21 -74
  105. package/src/pi/mutation-result.ts +74 -87
  106. package/src/pi/mutation-runner.ts +83 -75
  107. package/src/pi/output-budgets.test.ts +166 -0
  108. package/src/pi/path.ts +7 -0
  109. package/src/pi/read-tool.ts +151 -137
  110. package/src/pi/read.test.ts +39 -33
  111. package/src/pi/regex-worker-contract.ts +73 -0
  112. package/src/pi/regex-worker.ts +101 -0
  113. package/src/pi/registration.test.ts +111 -92
  114. package/src/pi/render.test.ts +193 -19
  115. package/src/pi/render.ts +137 -29
  116. package/src/pi/replace-regex.ts +11 -44
  117. package/src/pi/replace-tool.ts +38 -145
  118. package/src/pi/replace-worker-contract.ts +19 -0
  119. package/src/pi/replace-worker.ts +12 -8
  120. package/src/pi/replace.test.ts +93 -160
  121. package/src/pi/report-cause.ts +99 -0
  122. package/src/pi/report-failure.testing.ts +20 -0
  123. package/src/pi/report-schema.ts +512 -0
  124. package/src/pi/report.test.ts +276 -0
  125. package/src/pi/report.ts +288 -0
  126. package/src/pi/result-safety.test.ts +122 -427
  127. package/src/pi/rg-process.test.ts +78 -79
  128. package/src/pi/rg-process.ts +124 -177
  129. package/src/pi/rg-regex.test.ts +50 -0
  130. package/src/pi/rg-regex.ts +709 -0
  131. package/src/pi/text-stream.test.ts +67 -38
  132. package/src/pi/text-stream.ts +96 -75
  133. package/src/pi/tool-call.testing.ts +3 -39
  134. package/src/pi/write-tool.ts +45 -34
  135. package/src/pi/write.test.ts +45 -37
  136. package/src/testing/extension-loader.testing.ts +24 -0
  137. package/src/testing/installation.testing.ts +77 -0
  138. package/src/testing/process.testing.ts +33 -0
  139. package/src/testing/regex-host.testing.ts +20 -0
  140. package/src/testing/regex-translation-corpus.ts +308 -0
  141. package/src/testing/rg-line-listing.fixture.mjs +7 -0
  142. package/src/testing/run-tests.ts +47 -0
  143. package/src/testing/session.testing.ts +127 -0
  144. package/src/pi/rg-line-ranges.test.ts +0 -66
  145. package/src/pi/rg-line-ranges.ts +0 -75
  146. package/src/pi/rg-match-bytes.ts +0 -95
  147. package/src/pi/rg-text-view.ts +0 -192
  148. package/src/pi/tool-prompts.ts +0 -15
@@ -1,41 +1,39 @@
1
1
  /**
2
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.
3
+ * grep-scope admits paths, grep-candidates selects candidates with rg, grep-search matches
4
+ * them with native JavaScript (core/search), grep-output states the payload and every report
5
+ * fact, and grep-render draws the card. This module owns the schema, backend wiring, and
6
+ * execution order.
7
7
  * @module pi-hashline-edit/pi
8
8
  */
9
9
 
10
- import { type ToolDefinition } from "@earendil-works/pi-coding-agent";
10
+ 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";
14
+ import { renderOutputPreview, renderToolError, reportLines, withoutReport } from "./render.ts";
15
15
  import { type ForgetReceiptDetails, grepReceipt, withResultTag } from "./forget-tool.ts";
16
- import { normalizeLineEndings } from "../core/lines.ts";
17
16
  import { createAnchorFormatter } from "./anchor-format.ts";
18
- import { assembleGrepOutput, formatMatches, formatSearchWarnings } from "./grep-output.ts";
17
+ import { grepOutput } from "./grep-output.ts";
19
18
  import {
20
- assertValidRegex,
21
19
  filterExplicitFilesByGlob,
22
20
  toArray,
23
21
  resolveSearchPaths,
24
- } from "./grep-scope.ts";
25
- import {
26
- searchMatches,
27
- type GrepBackend,
28
22
  type SearchScope,
29
- type SearchFileSnapshot,
30
- } from "./grep-search.ts";
31
- export type { GrepBackend } from "./grep-search.ts";
23
+ } from "./grep-scope.ts";
24
+ import { searchFiles } from "./grep-search.ts";
32
25
  import { toDisplayLines } from "./grep-render.ts";
33
- import { probeRegex, resolveIgnoreCase, runRgPaths, type SearchModes } from "./rg-process.ts";
34
- import { runRgTextView } from "./rg-text-view.ts";
26
+ import { runRgLines, runRgPaths, type GrepBackend } from "./rg-process.ts";
27
+ import { smartIgnoreCase } from "../core/search-analysis.ts";
28
+ import { buildRegex } from "../core/regex.ts";
29
+ import { DEFAULT_GREP_FLAGS } from "../core/search.ts";
30
+ import { errorMessage } from "../core/errors.ts";
35
31
  import { GREP_CONTEXT_RANGE, POSITIVE_SAFE_INTEGER } from "./schema.ts";
36
32
  import { throwIfCancelled } from "./error-text.ts";
33
+ import { reportResult, runTool, type ReportDetails } from "./report.ts";
37
34
  import type { HashlineEditConfig } from "./config.ts";
38
- import { createArgumentPreparer } from "./argument-validation.ts";
35
+ import { createArgumentPreparer, type ReportArgumentIssue } from "./argument-validation.ts";
36
+ import { defaultOutputBudgets, type OutputBudgetProvider } from "./budgets.ts";
39
37
 
40
38
  /** Grep parameters; descriptions state the configured defaults. */
41
39
  function createGrepSchema({ defaultLimit, defaultContext }: HashlineEditConfig["grep"]) {
@@ -45,7 +43,7 @@ function createGrepSchema({ defaultLimit, defaultContext }: HashlineEditConfig["
45
43
  [Type.String({ minLength: 1 }), Type.Array(Type.String({ minLength: 1 }), { minItems: 1 })],
46
44
  {
47
45
  description:
48
- "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.",
46
+ "String or array of strings; an array matches any of them, so use it for alternatives instead of joining them with |. Regex syntax is JavaScript, as in replace.",
49
47
  },
50
48
  ),
51
49
  path: Type.Optional(
@@ -68,30 +66,35 @@ function createGrepSchema({ defaultLimit, defaultContext }: HashlineEditConfig["
68
66
  ],
69
67
  {
70
68
  description:
71
- "Filename glob, or an ordered array of them; prefix exclusions with !, e.g. ['*.ts', '!**/*.test.ts'].",
69
+ "Filename wildcards go here, not in path: a glob or an ordered array of them; prefix exclusions with !, e.g. ['*.ts', '!**/*.test.ts'].",
72
70
  },
73
71
  ),
74
72
  ),
75
73
  literal: Type.Boolean({
76
74
  description:
77
- "true: match the text exactly, including regex punctuation. false: ripgrep Rust regex, where foo(0) matches foo0.",
75
+ "true: match the text exactly, including regex punctuation; use it for names, paths, and code snippets. false: JavaScript regex, where foo(0) matches foo0; use it only for an intentional regex.",
78
76
  }),
77
+ flags: Type.Optional(
78
+ Type.String({
79
+ description: `JavaScript regex flags (default ${DEFAULT_GREP_FLAGS}); explicit flags replace the default. g is always enabled and repeated flags are ignored. Use u or v for Unicode mode, s for dotAll, and y for sticky matching.`,
80
+ }),
81
+ ),
79
82
  ignoreCase: Type.Optional(
80
83
  Type.Boolean({
81
84
  description:
82
- "true ignores case, false matches case; omitted uses smart-case for the whole query. Inline regex flags still apply.",
85
+ "true ignores case, false matches case; overrides the i flag. When omitted, the i flag ignores case; otherwise smart-case applies to the whole query, whatever other flags are given: any uppercase letter makes it case-sensitive (also when analysis is unavailable).",
83
86
  }),
84
87
  ),
85
88
  multiline: Type.Optional(
86
89
  Type.Boolean({
87
90
  description:
88
- "Match across lines (default false); content mode returns every line a match touches. The . wildcard does not match newlines; use \\n or (?s).",
91
+ "Match across lines (default false); content mode returns every line a match touches. \\n matches LF and CRLF.",
89
92
  }),
90
93
  ),
91
94
  context: Type.Optional(
92
95
  Type.Number({
93
96
  ...GREP_CONTEXT_RANGE,
94
- description: `Lines shown before and after each match (${GREP_CONTEXT_RANGE.minimum}-${GREP_CONTEXT_RANGE.maximum}, default ${defaultContext}); display only, not matched.`,
97
+ description: `Lines shown before and after each match (${GREP_CONTEXT_RANGE.minimum}-${GREP_CONTEXT_RANGE.maximum}, default ${defaultContext}); display only, not matched. Use 3-5 when searching code to edit.`,
95
98
  }),
96
99
  ),
97
100
  limit: Type.Optional(
@@ -103,7 +106,7 @@ function createGrepSchema({ defaultLimit, defaultContext }: HashlineEditConfig["
103
106
  outputMode: Type.Optional(
104
107
  Type.Union([Type.Literal("content"), Type.Literal("files"), Type.Literal("count")], {
105
108
  description:
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.',
109
+ '"content" (default): matches/context with anchors for valid UTF-8 or plain previews otherwise; "files": paths; "count": matching lines per file and total. Use files or count when only paths or counts are needed. All modes share limit.',
107
110
  }),
108
111
  ),
109
112
  },
@@ -111,14 +114,46 @@ function createGrepSchema({ defaultLimit, defaultContext }: HashlineEditConfig["
111
114
  );
112
115
  }
113
116
  type GrepSchema = ReturnType<typeof createGrepSchema>;
117
+ /** How grep presents matches; grep-output formats each mode. */
118
+ export type GrepOutputMode = NonNullable<Static<GrepSchema>["outputMode"]>;
114
119
  type GrepTool = ToolDefinition<
115
120
  GrepSchema,
116
- ({ incomplete?: true } & ForgetReceiptDetails) | undefined
121
+ ({ incomplete?: true } & ForgetReceiptDetails & Partial<ReportDetails>) | undefined
117
122
  >;
123
+ /** Validate JavaScript syntax once; the search never rejects a pattern V8 accepts. */
124
+ function checkGrepArguments(args: unknown, report: ReportArgumentIssue): void {
125
+ const { pattern, literal, flags } = (args ?? {}) as Record<string, unknown>;
126
+ if (typeof literal !== "boolean" || (flags !== undefined && typeof flags !== "string")) return;
127
+ try {
128
+ buildRegex("", false, flags ?? DEFAULT_GREP_FLAGS);
129
+ } catch (error) {
130
+ report("flags", errorMessage(error));
131
+ return;
132
+ }
133
+ if (literal) return;
134
+ const fields = Array.isArray(pattern)
135
+ ? pattern.map((value, index) => [`pattern[${index}]`, value] as const)
136
+ : [["pattern", pattern] as const];
137
+ for (const [field, value] of fields) {
138
+ if (typeof value !== "string" || value === "") continue;
139
+ try {
140
+ buildRegex(value, true, flags ?? DEFAULT_GREP_FLAGS);
141
+ } catch (error) {
142
+ report(field, errorMessage(error));
143
+ }
144
+ }
145
+ }
146
+
147
+ /** The grep card shows the forget id only on the forget card. */
148
+ const GREP_CARD_SHOWN = new Set(["resultId"]);
118
149
 
119
150
  /** Build the production grep override (a ToolDefinition fragment for registerTool). */
120
- export function makeGrepOverride(cwd: string, config: HashlineEditConfig) {
121
- return makeGrepOverrideWithBackend(cwd, config, {});
151
+ export function makeGrepOverride(
152
+ cwd: string,
153
+ config: HashlineEditConfig,
154
+ budgets: OutputBudgetProvider = defaultOutputBudgets,
155
+ ) {
156
+ return makeGrepOverrideWithBackend(cwd, config, {}, budgets);
122
157
  }
123
158
 
124
159
  /** @internal — build a grep override with deterministic process backends for tests. */
@@ -126,33 +161,24 @@ export function makeGrepOverrideWithBackend(
126
161
  cwd: string,
127
162
  config: HashlineEditConfig,
128
163
  overrides: Partial<GrepBackend>,
164
+ budgets: OutputBudgetProvider = defaultOutputBudgets,
129
165
  ) {
130
166
  const { hashLen } = config;
131
167
  const grepSchema = createGrepSchema(config.grep);
132
- const backend: GrepBackend = {
133
- search: runRgTextView,
134
- runRgPaths,
135
- resolveIgnoreCase,
136
- probeRegex,
137
- ...overrides,
138
- };
168
+ const backend: GrepBackend = { runRgPaths, runRgLines, ...overrides };
139
169
 
140
170
  return {
141
171
  name: "grep" as const,
142
172
  label: "grep",
143
173
  description:
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.",
145
- promptSnippet: "Search file contents with ripgrep",
174
+ "Search file contents. 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. NUL-containing files are skipped. Directory searches respect ignore rules and skip .git and linked directories. Use grep instead of rg or grep in a shell to search files; use the shell only for ignored, .git, or linked directories, or to filter another command's output.",
175
+ promptSnippet: "Search file contents",
146
176
  promptGuidelines: [
147
- "Prefer grep for file-content searches; use another tool for ignored or linked directories.",
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.",
150
- "In grep, use a pattern array for alternatives instead of joining them with |, and context:3-5 when searching code to edit.",
151
- "In grep, use multiline:true for cross-line matches and outputMode files or count when only paths or counts are needed.",
152
- "Copy grep anchors directly into edit; read the full line before rewriting from a partial preview.",
177
+ "When you need several independent searches, send them as separate grep calls in one response; they run in parallel.",
178
+ "Copy grep anchors directly into edit.",
153
179
  ],
154
180
  parameters: grepSchema,
155
- prepareArguments: createArgumentPreparer("grep", grepSchema),
181
+ prepareArguments: createArgumentPreparer("grep", grepSchema, checkGrepArguments, budgets),
156
182
 
157
183
  renderShell: "default" as const,
158
184
 
@@ -168,7 +194,7 @@ export function makeGrepOverrideWithBackend(
168
194
  const pathText = Array.isArray(rawPath) ? rawPath.join(" ") : String(rawPath ?? ".");
169
195
  let text =
170
196
  theme.fg("toolTitle", theme.bold("grep ")) +
171
- theme.fg("accent", `/${patternText}/`) +
197
+ theme.fg("accent", `/${patternText}/${args?.flags ?? ""}`) +
172
198
  theme.fg("toolOutput", ` in ${pathText}`);
173
199
  if (args?.glob) text += theme.fg("toolOutput", ` (${toArray(args.glob).join(", ")})`);
174
200
  if (args?.outputMode && args.outputMode !== "content")
@@ -185,8 +211,16 @@ export function makeGrepOverrideWithBackend(
185
211
  ) {
186
212
  if (isPartial) return new Text(theme.fg("warning", "Searching…"), 0, 0);
187
213
  if (context?.isError) return renderToolError(result, theme, expanded);
188
- const out = result.content?.[0]?.type === "text" ? result.content[0].text : "";
189
- return renderOutputPreview(toDisplayLines(out, theme), expanded, theme);
214
+ const payload = withoutReport(result).content[0];
215
+ const report = result.details?.report;
216
+ return renderOutputPreview(
217
+ [
218
+ ...(payload?.type === "text" ? toDisplayLines(payload.text, theme) : []),
219
+ ...(report ? reportLines(report, theme, GREP_CARD_SHOWN) : []),
220
+ ],
221
+ expanded,
222
+ theme,
223
+ );
190
224
  },
191
225
 
192
226
  async execute(
@@ -195,104 +229,80 @@ export function makeGrepOverrideWithBackend(
195
229
  signal: AbortSignal | undefined,
196
230
  _onUpdate: Parameters<GrepTool["execute"]>[3],
197
231
  ) {
198
- throwIfCancelled(signal);
199
- const anchors = createAnchorFormatter(hashLen);
200
- const warnings: string[] = [];
201
-
202
- const patterns = toArray(params.pattern);
203
- const effectiveLimit = params.limit ?? config.grep.defaultLimit;
204
- const context = params.context ?? config.grep.defaultContext;
205
- const rgPath = bundledRgPath;
206
- const outputMode: "content" | "files" | "count" = params.outputMode ?? "content";
207
- const multiline = params.multiline ?? false;
208
- const globs = toArray(params.glob);
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
- }
216
- const matcherIgnoreCase = await backend.resolveIgnoreCase(
217
- rgPath,
218
- patterns,
219
- { literal, multiline },
220
- params.ignoreCase,
221
- signal,
222
- );
223
- const modes: SearchModes = { literal, ignoreCase: matcherIgnoreCase, multiline };
224
- const ctx = context;
225
- const { searchPaths, pathInfo } = await resolveSearchPaths(cwd, params.path);
226
- let scope: SearchScope = {
227
- globs,
228
- noIgnore: false,
229
- follow: false,
230
- searchPaths,
231
- };
232
-
233
- scope = {
234
- ...scope,
235
- searchPaths: await filterExplicitFilesByGlob(
232
+ const budget = budgets();
233
+ return runTool("grep", { path: params.path, signal, budget }, async () => {
234
+ throwIfCancelled(signal);
235
+ const warnings: string[] = [];
236
+ const patterns = toArray(params.pattern);
237
+ const effectiveLimit = params.limit ?? config.grep.defaultLimit;
238
+ const outputMode = params.outputMode ?? "content";
239
+ const { literal } = params;
240
+ const flags = new Set(params.flags ?? DEFAULT_GREP_FLAGS);
241
+ const ignoreCase =
242
+ params.ignoreCase ??
243
+ (flags.has("i") || smartIgnoreCase(patterns, literal, [...flags].join("")));
244
+ if (ignoreCase) flags.add("i");
245
+ else flags.delete("i");
246
+ const query = {
247
+ patterns,
248
+ literal,
249
+ flags: [...flags].join(""),
250
+ multiline: params.multiline ?? false,
251
+ };
252
+ const { searchPaths, pathInfo } = await resolveSearchPaths(cwd, params.path);
253
+ const unfiltered: SearchScope = {
254
+ globs: toArray(params.glob),
255
+ noIgnore: false,
256
+ follow: false,
257
+ searchPaths,
258
+ };
259
+ const scope: SearchScope = {
260
+ ...unfiltered,
261
+ searchPaths: await filterExplicitFilesByGlob(
262
+ backend,
263
+ bundledRgPath,
264
+ unfiltered,
265
+ pathInfo,
266
+ signal,
267
+ warnings,
268
+ ),
269
+ };
270
+ const search = await searchFiles({
236
271
  backend,
237
- rgPath,
272
+ rgPath: bundledRgPath,
238
273
  scope,
239
- pathInfo,
274
+ query,
275
+ limit: effectiveLimit,
276
+ timeoutMs: config.grep.regexTimeoutMs,
240
277
  signal,
241
278
  warnings,
242
- ),
243
- };
244
-
245
- const result =
246
- scope.searchPaths.length === 0
247
- ? { raw: [], matchLimitReached: false, snapshots: new Map<string, SearchFileSnapshot>() }
248
- : await searchMatches({
249
- backend,
250
- rgPath,
251
- scope,
252
- patterns,
253
- modes,
254
- limit: effectiveLimit,
255
- outputMode,
256
- signal,
257
- warnings,
258
- });
259
- const { raw, matchLimitReached } = result;
260
-
261
- if (raw.length === 0) {
262
- if (warnings.length)
263
- throw new Error(`No matches confirmed.${formatSearchWarnings(warnings)}`);
264
- return {
265
- content: [{ type: "text" as const, text: "No matches found" }],
266
- details: undefined,
279
+ });
280
+ const { payload, facts, incomplete } = await grepOutput({
281
+ cwd,
282
+ search,
283
+ outputMode,
284
+ context: params.context ?? config.grep.defaultContext,
285
+ anchors: createAnchorFormatter(hashLen),
286
+ signal,
287
+ warnings,
288
+ effectiveLimit,
289
+ budget,
290
+ });
291
+ const parts = {
292
+ report: { tool: "grep" as const, path: params.path, ...facts },
293
+ payload: payload === undefined ? [] : [{ type: "text" as const, text: payload }],
294
+ details: incomplete ? { incomplete: true as const } : undefined,
267
295
  };
268
- }
269
-
270
- const { blocks, linesTruncated } = await formatMatches({
271
- cwd,
272
- raw,
273
- outputMode,
274
- context: ctx,
275
- anchors,
276
- signal,
277
- warnings,
278
- searchSnapshots: result.snapshots,
296
+ // Only matched content-mode rows are file text; paths and counts have nothing to forget.
297
+ if (outputMode !== "content" || payload === undefined)
298
+ return reportResult(parts.report, parts.payload, parts.details);
299
+ return withResultTag(toolCallId, parts, config.forget, () =>
300
+ grepReceipt(patterns, facts.matches, facts.files, {
301
+ limitReached: search.matchLimitReached,
302
+ incomplete,
303
+ }),
304
+ );
279
305
  });
280
- const output = assembleGrepOutput({
281
- blocks,
282
- warnings,
283
- outputMode,
284
- matchLimitReached,
285
- effectiveLimit,
286
- linesTruncated,
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
- );
296
306
  },
297
307
  } satisfies GrepTool;
298
308
  }
@@ -0,0 +1,4 @@
1
+ import { createJiti } from "jiti";
2
+
3
+ // Installed packages need an explicit TypeScript loader in worker threads.
4
+ await createJiti(import.meta.url).import("./grep-worker.ts");
@@ -0,0 +1,14 @@
1
+ /** grep's regex worker: runs core/search on the requests of grep-search's pool. */
2
+ import { parentPort } from "node:worker_threads";
3
+ import { searchLines, searchText, type LineSearchInput, type SearchInput } from "../core/search.ts";
4
+ import { workerFailure } from "./report-cause.ts";
5
+
6
+ // Query syntax and options have already passed the tool entry point.
7
+ parentPort!.on("message", (input: SearchInput | LineSearchInput) => {
8
+ try {
9
+ const result = "lines" in input ? searchLines(input) : searchText(input);
10
+ parentPort!.postMessage({ result });
11
+ } catch (error) {
12
+ parentPort!.postMessage(workerFailure(error));
13
+ }
14
+ });