pikuri-workspace 0.0.7 → 0.2.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.
@@ -0,0 +1,310 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Pikuri
4
+ module Workspace
5
+ module Search
6
+ # The +glob+ tool — list files matching a glob pattern via +rg --files+,
7
+ # sorted by mtime (newest first). +Glob.new(workspace: ws)+ produces a tool
8
+ # wired like any bundled tool's (workspace captured by the +execute+ closure,
9
+ # no confirmer — read-only).
10
+ #
11
+ # == Why a separate tool from Grep
12
+ #
13
+ # The unique capability is *mtime-descending sort* — "what's been touched
14
+ # recently", which Grep can't express. The rest is reachable via Grep with
15
+ # +pattern="."+, but a separate tool keeps Read/Grep/Glob three clean roles:
16
+ # read one file, search content, list files by name.
17
+ #
18
+ # == ripgrep dependency
19
+ #
20
+ # Hard: {.check_binaries!} runs in +initialize+ and raises if +rg+ isn't on
21
+ # +PATH+. Each tool owns its probe so construction order doesn't matter.
22
+ #
23
+ # == Argv & filter pipeline
24
+ #
25
+ # rg --files --color=never --hidden --glob '!.git/*' -- <path-or-dot>
26
+ # # …then filter the list in Ruby with File.fnmatch?
27
+ #
28
+ # The user pattern is NOT passed to rg as +--glob+: rg's +--glob+ *"always
29
+ # overrides any other ignore logic"*, so it would re-include +.gitignore+'d
30
+ # files, breaking the gitignore-respect promise. Instead rg produces the
31
+ # full gitignore-respecting list and Ruby filters with
32
+ # +File.fnmatch?(pattern, p, FNM_PATHNAME | FNM_EXTGLOB | FNM_DOTMATCH)+ —
33
+ # the three flags covering +**+ recursion, +{a,b}+ alternation, and dotfiles
34
+ # (matching +--hidden+). The +.git/+ exclusion stays on the rg side (an
35
+ # explicit +--glob+, so it survives +--no-ignore+). Output +./+ prefixes
36
+ # (from search path +.+) are stripped post-rg.
37
+ #
38
+ # == Credential paths
39
+ #
40
+ # Pruned twice: +rg --glob '!…'+ keeps rg out of the subtree, and a
41
+ # {Filesystem#denied?} pass over the surviving list is the guarantee if
42
+ # that ever goes partial (see {Utils.denied_globs}).
43
+ #
44
+ # == Sort / truncation / exit codes
45
+ #
46
+ # mtime-descending in Ruby (path-ascending tiebreaker), one +stat+ per
47
+ # result — bounded in practice by rg's +.gitignore+ filter. Output
48
+ # head-truncated to {MAX_BYTES} *after* sort so the newest rows survive; the
49
+ # exit-2 error blob shares the same ceiling ({.truncate_error} — rg emits one
50
+ # diagnostic per unreadable path). Exit +0+ → listing with footer; +1+ → "No
51
+ # files match"; +2+ → +"Error: ripgrep: ..."+.
52
+ #
53
+ # == Refusals (all as +"Error: ..."+)
54
+ #
55
+ # Empty +pattern+; +path+ is a regular file (→ read tool); +path+ not found;
56
+ # +path+ outside the workspace ({Filesystem::Error}); an oversized root (+/+
57
+ # or the whole home dir). The oversized-root refusal doesn't dead-end: it
58
+ # hands back a one-level listing of the root's entries so the model can
59
+ # pick a subdir as +path+ and retry with no extra call (see
60
+ # {Utils.oversized_root_refusal}).
61
+ #
62
+ # Sharing: +P_one_agent+ — as {Pikuri::Workspace::FileList}: no state of
63
+ # its own, but the {Pikuri::Workspace::Workspace} it searches is one
64
+ # agent's tree.
65
+ class Glob < Pikuri::Tool
66
+ # @return [Integer] hard byte cap on combined rg output. Same value as
67
+ # {Grep::MAX_BYTES}; re-declared rather than cross-referenced because
68
+ # Zeitwerk's eager-load order between siblings isn't guaranteed.
69
+ MAX_BYTES = 50 * 1024
70
+
71
+ # @return [String] human-readable {MAX_BYTES} for the truncation marker.
72
+ MAX_BYTES_LABEL = "#{MAX_BYTES / 1024} KB"
73
+
74
+ # Description shown to the LLM (opencode-shape). Per-parameter constraints
75
+ # live in the parameter descriptions.
76
+ #
77
+ # @return [String]
78
+ DESCRIPTION = <<~DESC
79
+ List files matching a glob pattern, sorted by modification time (newest first).
80
+
81
+ Usage:
82
+ - Respects `.gitignore` by default; set `include_gitignored: true` to also list ignored files.
83
+ - Default search root is the workspace root; pass `path` to narrow to a subdirectory.
84
+ - Use `glob` to find files by name; use `grep` to find files by content.
85
+ - Output is sorted by mtime descending — recently-touched files come first, so broad patterns still surface relevant files near the top.
86
+ - Output is truncated to #{MAX_BYTES_LABEL}; refine the pattern or narrow `path` if the response ends in a truncation marker.
87
+ DESC
88
+
89
+ # @param workspace [Workspace] captured for path resolution and as +chdir+
90
+ # for rg; path arguments route through +resolve_for_read+.
91
+ # @raise [RuntimeError] if +rg+ isn't on +PATH+ (fail-loud at construction).
92
+ # @return [Glob]
93
+ def initialize(workspace:)
94
+ Glob.send(:check_binaries!)
95
+ super(
96
+ name: 'glob',
97
+ description: DESCRIPTION,
98
+ parameters: Parameters.build { |p|
99
+ p.required_string :pattern,
100
+ 'Glob pattern: ** matches any number of ' \
101
+ 'directories, * matches any filename chars ' \
102
+ '(not /), {a,b} is alternation. E.g. ' \
103
+ '"src/**/*.{ts,tsx}" finds every TS/TSX file ' \
104
+ 'anywhere under src/.'
105
+ p.optional_string :path,
106
+ 'Directory to search in (e.g. "lib" or ' \
107
+ '"spec/pikuri"). Relative paths resolve against ' \
108
+ 'the workspace root. Defaults to the workspace ' \
109
+ 'root if missing.'
110
+ p.optional_boolean :include_gitignored,
111
+ 'Also list files excluded by .gitignore. ' \
112
+ 'Defaults to false, e.g. true.'
113
+ },
114
+ execute: lambda { |pattern:, path: nil, include_gitignored: false|
115
+ Glob.search(workspace: workspace, pattern: pattern, path: path,
116
+ include_gitignored: include_gitignored)
117
+ },
118
+ # Filenames, not contents — but a path can be as sensitive as a file
119
+ # (+~/medical/2026-diagnosis.pdf+) and is as attacker-authorable
120
+ # (a cloned dep names its own files), so this reads the same as Read.
121
+ trifecta_legs: Tool::TrifectaLegs.new(
122
+ private: workspace.filesystem.private?,
123
+ untrusted: workspace.filesystem.trusted? ? :none : :hard,
124
+ egress_payload_review: :no_egress
125
+ )
126
+ )
127
+ end
128
+
129
+ # Validate inputs, resolve the path, spawn rg, mtime-sort, head-truncate,
130
+ # render. Returns the listing, a "no files match" message, or +"Error:
131
+ # ..."+.
132
+ #
133
+ # @param workspace [Workspace]
134
+ # @param pattern [String]
135
+ # @param path [String, nil]
136
+ # @param include_gitignored [Boolean] pass +--no-ignore+ to rg, so
137
+ # +.gitignore+'d files are listed too. Defaults to false.
138
+ # @return [String]
139
+ def self.search(workspace:, pattern:, path:, include_gitignored: false)
140
+ return Tool::Result.error('empty pattern.') if pattern.empty?
141
+
142
+ search_target = '.'
143
+ resolved_root = workspace.project_root
144
+ if path
145
+ resolved = workspace.resolve_for_read(path)
146
+ return Tool::Result.error("path not found: #{path}") unless resolved.exist?
147
+ if resolved.file?
148
+ return Tool::Result.error("#{path} is a file, not a directory; use the read tool to view it.")
149
+ end
150
+
151
+ resolved_root = resolved
152
+ rel = resolved.relative_path_from(workspace.project_root).to_s
153
+ search_target = rel
154
+ end
155
+
156
+ if (refusal = Utils.oversized_root_refusal(resolved_root, filesystem: workspace.filesystem,
157
+ verb: 'list'))
158
+ return Tool::Result.error(refusal)
159
+ end
160
+
161
+ argv = build_argv(path: search_target, include_gitignored: include_gitignored,
162
+ denied_globs: Utils.denied_globs(filesystem: workspace.filesystem,
163
+ root: workspace.project_root))
164
+ result = Pikuri::Subprocess.spawn(*argv, chdir: workspace.project_root.to_s).wait
165
+ exit_code = result.status.exitstatus
166
+
167
+ case exit_code
168
+ when 0
169
+ format_output(result.output, workspace: workspace,
170
+ pattern: pattern, path: path)
171
+ when 1
172
+ no_match_message(pattern: pattern, path: path)
173
+ else
174
+ Tool::Result.error("ripgrep: #{truncate_error(result.output, exit_code)}")
175
+ end
176
+ rescue Filesystem::Error => e
177
+ Tool::Result.error(e.message)
178
+ end
179
+
180
+ # @return [Integer] flags for {File.fnmatch?}: +FNM_PATHNAME+ for
181
+ # +**+ recursion + path-aware +/+ matching, +FNM_EXTGLOB+ for
182
+ # +{a,b}+ alternation, +FNM_DOTMATCH+ to match dotfiles (rg
183
+ # does this when +--hidden+ is set).
184
+ FNMATCH_FLAGS = File::FNM_PATHNAME | File::FNM_EXTGLOB | File::FNM_DOTMATCH
185
+
186
+ # Build the +rg+ argv. The user pattern is NOT passed to rg — see the
187
+ # class header (rg's +--glob+ overrides +.gitignore+). The +.git/+
188
+ # exclusion is an explicit +--glob+, so it survives +--no-ignore+.
189
+ #
190
+ # @return [Array<String>]
191
+ def self.build_argv(path:, include_gitignored:, denied_globs:)
192
+ argv = [
193
+ 'rg',
194
+ '--files',
195
+ '--color=never',
196
+ '--hidden',
197
+ '--glob', '!.git/*'
198
+ ]
199
+ argv.concat(denied_globs)
200
+ argv << '--no-ignore' if include_gitignored
201
+ argv.push('--', path)
202
+ end
203
+ private_class_method :build_argv
204
+
205
+ # Strip the +./+ prefix, filter to the user pattern with +fnmatch+,
206
+ # mtime-sort descending (path-ascending tiebreaker), head-truncate at
207
+ # {MAX_BYTES}, append a count footer.
208
+ #
209
+ # @return [Tool::Result] the listing, carrying +"Found 12 files"+
210
+ def self.format_output(raw, workspace:, pattern:, path:)
211
+ all_paths = raw.split("\n").reject(&:empty?).map { |p| p.sub(%r{\A\./}, '') }
212
+ paths = all_paths.select { |p| File.fnmatch?(pattern, p, FNMATCH_FLAGS) }
213
+ # The guarantee, after build_argv's pruning did the cheap 99%.
214
+ paths = paths.reject { |p| workspace.filesystem.denied?(workspace.project_root + p) }
215
+ return no_match_message(pattern: pattern, path: path) if paths.empty?
216
+
217
+ sorted = mtime_sort(paths, workspace.project_root)
218
+ joined = sorted.join("\n") + "\n"
219
+ content, truncation_marker = head_truncate(joined)
220
+ stripped = content.chomp
221
+ count = stripped.split("\n").size
222
+
223
+ footer = "Found #{Pikuri::Tool.pluralize(count, 'file', 'files')}."
224
+ Tool::Result.new(content: [stripped, '', footer + truncation_marker].join("\n"),
225
+ summary: "Found #{Pikuri::Tool.pluralize(count, 'file', 'files')}")
226
+ end
227
+ private_class_method :format_output
228
+
229
+ # mtime descending; path ascending for stable order on ties.
230
+ #
231
+ # @return [Array<String>]
232
+ def self.mtime_sort(paths, base)
233
+ paths
234
+ .map { |p| [p, mtime_of(base + p)] }
235
+ .sort_by { |(p, m)| [-m, p] }
236
+ .map(&:first)
237
+ end
238
+ private_class_method :mtime_sort
239
+
240
+ # @return [Float] epoch-seconds mtime; 0 for paths we can't stat
241
+ # (race between rg listing and our stat, deleted symlinks,
242
+ # etc.). The fallback puts unstattable entries at the bottom.
243
+ def self.mtime_of(absolute)
244
+ File.mtime(absolute).to_f
245
+ rescue Errno::ENOENT
246
+ 0.0
247
+ end
248
+ private_class_method :mtime_of
249
+
250
+ # Head-truncate +raw+ to {MAX_BYTES}. Returns the content and a marker
251
+ # (empty if no truncation).
252
+ #
253
+ # @return [Array(String, String)]
254
+ def self.head_truncate(raw)
255
+ Utils.head_truncate(raw, max_bytes: MAX_BYTES, hint: 'refine pattern or path')
256
+ end
257
+ private_class_method :head_truncate
258
+
259
+ # Head-truncate an rg error blob to {MAX_BYTES}. rg writes one diagnostic
260
+ # per unreadable path (broken symlinks, permission denials — a listing
261
+ # escaping into +~/.local/share/docker+ overlays), so on exit 2 the merged
262
+ # stderr can run to hundreds of KB and overflow context; this gives the
263
+ # error path the same ceiling as the success path.
264
+ #
265
+ # @param raw [String] rg's merged stdout+stderr
266
+ # @param exit_code [Integer] for the empty-output fallback
267
+ # @return [String]
268
+ def self.truncate_error(raw, exit_code)
269
+ stderr = raw.strip
270
+ return "exited #{exit_code}" if stderr.empty?
271
+
272
+ content, marker = head_truncate(stderr)
273
+ content + marker
274
+ end
275
+ private_class_method :truncate_error
276
+
277
+ # @return [Tool::Result] the "nothing matched" observation, carrying
278
+ # +"Found 0 files"+
279
+ def self.no_match_message(pattern:, path:)
280
+ base = "No files match pattern '#{pattern}'"
281
+ base += " in #{path}" if path
282
+ Tool::Result.new(content: "#{base}.", summary: 'Found 0 files')
283
+ end
284
+ private_class_method :no_match_message
285
+
286
+ # Verify +rg+ is on +PATH+ (via {Pikuri::Subprocess.spawn}, honoring the
287
+ # subprocess seam). Missing → +Errno::ENOENT+; installed → exit 0.
288
+ #
289
+ # @return [void]
290
+ # @raise [RuntimeError] if rg is missing
291
+ def self.check_binaries!
292
+ result = Pikuri::Subprocess.spawn('rg', '--version', chdir: '/').wait
293
+ return if result.status.success?
294
+
295
+ raise install_hint
296
+ rescue Errno::ENOENT
297
+ raise install_hint
298
+ end
299
+ private_class_method :check_binaries!
300
+
301
+ # @return [String]
302
+ def self.install_hint
303
+ "Glob requires 'rg' (ripgrep) on PATH; install via your " \
304
+ "distro's package manager (e.g. 'apt install ripgrep')."
305
+ end
306
+ private_class_method :install_hint
307
+ end
308
+ end
309
+ end
310
+ end
@@ -0,0 +1,353 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Pikuri
4
+ module Workspace
5
+ module Search
6
+ # The +grep+ tool — content search across the workspace via +ripgrep+.
7
+ # +Grep.new(workspace: ws)+ produces a tool wired like any bundled tool's
8
+ # (workspace captured by the +execute+ closure, no confirmer — read-only).
9
+ #
10
+ # == ripgrep dependency
11
+ #
12
+ # Hard: {.check_binaries!} runs in +initialize+ and raises if +rg+ isn't on
13
+ # +PATH+. No Ruby fallback — replicating rg's Rust-regex dialect, globs, and
14
+ # +.gitignore+ parsing is a dead end. The failure message includes the
15
+ # install hint.
16
+ #
17
+ # == Argv
18
+ #
19
+ # rg --line-number --color=never --no-heading --with-filename \
20
+ # --hidden --max-columns=2000 --max-columns-preview --sort=path \
21
+ # [-i] [--glob <g>] [--files-with-matches|--count-matches] \
22
+ # -- <pattern> <path-or-dot>
23
+ #
24
+ # * +--no-heading+ + +--with-filename+ → flat +path:line:content+ rows even
25
+ # for a single-file search (rg suppresses the filename there by default).
26
+ # * +--hidden+ → search dotfiles (still respects +.gitignore+).
27
+ # * +--max-columns=2000 --max-columns-preview+ → rg truncates long lines
28
+ # server-side with a preview marker.
29
+ # * +--sort=path+ → deterministic (single-threaded; fine under ~10k files).
30
+ # * The subprocess is *always* given an explicit path arg: {Subprocess}'s
31
+ # +popen2e+ gives the child a piped stdin, and rg's no-path heuristic would
32
+ # then search that (closed) stdin and match nothing. Output +./+ prefixes
33
+ # (from path +.+) are stripped post-rg.
34
+ #
35
+ # == Output modes
36
+ #
37
+ # +content+ (default, +path:line:content+) · +files_with_matches+ (paths) ·
38
+ # +count+ (+path:count+). Use +files_with_matches+ to scope a broad search
39
+ # cheaply before paying for +content+.
40
+ # The cheap modes and the {MAX_BYTES} cap are one budget lever, confirmed
41
+ # as such by an outside-model review (Grok 4.6, 2026-08): collapsing to a
42
+ # +content+-only grep is a regression, not a simplification.
43
+ #
44
+ # == Credential paths
45
+ #
46
+ # Pruned twice: +rg --glob '!…'+ keeps rg out of the subtree, and every
47
+ # surviving output line whose path sits under a denied root is dropped —
48
+ # the guarantee if the pruning ever goes partial (see
49
+ # {Utils.reject_denied_lines}). Without it a single
50
+ # +grep 'BEGIN PRIVATE KEY'+ returns what {Read} refuses to open.
51
+ #
52
+ # == Truncation / exit codes
53
+ #
54
+ # Head-truncated to {MAX_BYTES} (head-only — grep tails carry less signal;
55
+ # opposite bias from a shell tool, whose tail holds the error), cut at a line boundary with a
56
+ # marker. The exit-2 error blob shares the ceiling ({.truncate_error} — rg
57
+ # emits one diagnostic per unreadable path). Exit +0+ → results with footer;
58
+ # +1+ → "No matches"; +2+ → +"Error: ripgrep: ..."+.
59
+ #
60
+ # == Refusals (all as +"Error: ..."+)
61
+ #
62
+ # Empty +pattern+; unknown +output_mode+; path outside the workspace
63
+ # ({Filesystem::Error}); nonexistent path; an oversized root (+/+ or the
64
+ # whole home dir). The oversized-root refusal doesn't dead-end: it hands
65
+ # back a one-level listing of the root's entries so the model can pick a
66
+ # subdir as +path+ and retry with no extra call (see
67
+ # {Utils.oversized_root_refusal}).
68
+ #
69
+ # Sharing: +P_one_agent+, as {Glob} — stateless in itself, bound to one
70
+ # agent's {Pikuri::Workspace::Workspace}. Each call shells out to a fresh
71
+ # +rg+, so concurrent searches don't interact.
72
+ class Grep < Pikuri::Tool
73
+ # @return [Integer] hard byte cap on combined rg output. Same value as
74
+ # {Read::MAX_BYTES}.
75
+ MAX_BYTES = 50 * 1024
76
+
77
+ # @return [String] human-readable {MAX_BYTES} for the truncation marker.
78
+ MAX_BYTES_LABEL = "#{MAX_BYTES / 1024} KB"
79
+
80
+ # @return [Integer] per-line cap passed to rg's +--max-columns+; long
81
+ # lines are truncated server-side with a preview marker.
82
+ MAX_LINE_LENGTH = 2000
83
+
84
+ # @return [Array<String>] valid +output_mode+ values.
85
+ OUTPUT_MODES = %w[content files_with_matches count].freeze
86
+
87
+ # @return [String] default +output_mode+.
88
+ DEFAULT_OUTPUT_MODE = 'content'
89
+
90
+ # Description shown to the LLM (opencode-shape). Per-parameter constraints
91
+ # live in the parameter descriptions.
92
+ #
93
+ # @return [String]
94
+ DESCRIPTION = <<~DESC
95
+ Search file contents for a regex pattern across the workspace.
96
+
97
+ Usage:
98
+ - Wraps `ripgrep` — regex syntax is rg's Rust-regex dialect (mostly PCRE-compatible; no lookbehind).
99
+ - Default search root is the workspace root; pass `path` to narrow to a file or subdirectory.
100
+ - Respects `.gitignore` by default; set `include_gitignored: true` to also search ignored files.
101
+ - Use `files_with_matches` first to scope a broad search, then `content` (or `read`) to investigate — saves tokens.
102
+ - Output is truncated to #{MAX_BYTES_LABEL}; refine the pattern or narrow `path` if the response ends in a truncation marker.
103
+ - Long lines are truncated to #{MAX_LINE_LENGTH} chars with a preview marker; use `read` to see full lines.
104
+ DESC
105
+
106
+ # @param workspace [Workspace] captured for path resolution and as +chdir+
107
+ # for rg; path arguments route through +resolve_for_read+.
108
+ # @raise [RuntimeError] if +rg+ isn't on +PATH+ (fail-loud at construction).
109
+ # @return [Grep]
110
+ def initialize(workspace:)
111
+ Grep.send(:check_binaries!)
112
+ super(
113
+ name: 'grep',
114
+ description: DESCRIPTION,
115
+ parameters: Parameters.build { |p|
116
+ p.required_string :pattern,
117
+ 'Regex pattern to search for (rg Rust-regex ' \
118
+ 'dialect), e.g. "def\s+\w+" or "TODO".'
119
+ p.optional_string :path,
120
+ 'File or directory to search (e.g. "lib" or ' \
121
+ '"src/app.rb"). Relative paths resolve against ' \
122
+ 'the workspace root. Defaults to the workspace root.'
123
+ p.optional_string :glob,
124
+ 'Filename glob restricting which files are ' \
125
+ 'searched: ** matches any number of ' \
126
+ 'directories, {a,b} is alternation. E.g. ' \
127
+ '"*.rb" or "src/**/*.{ts,tsx}".'
128
+ p.optional_boolean :case_insensitive,
129
+ 'Match case-insensitively. Defaults to false, e.g. true.'
130
+ p.optional_string :output_mode,
131
+ "One of #{OUTPUT_MODES.join(', ')}. Defaults to " \
132
+ "#{DEFAULT_OUTPUT_MODE}, e.g. \"files_with_matches\"."
133
+ p.optional_boolean :include_gitignored,
134
+ 'Also search files excluded by .gitignore. ' \
135
+ 'Defaults to false, e.g. true.'
136
+ },
137
+ execute: lambda { |pattern:, path: nil, glob: nil, case_insensitive: false,
138
+ output_mode: DEFAULT_OUTPUT_MODE, include_gitignored: false|
139
+ Grep.search(workspace: workspace, pattern: pattern, path: path,
140
+ glob: glob, case_insensitive: case_insensitive,
141
+ output_mode: output_mode, include_gitignored: include_gitignored)
142
+ },
143
+ trifecta_legs: Tool::TrifectaLegs.new(
144
+ private: workspace.filesystem.private?,
145
+ untrusted: workspace.filesystem.trusted? ? :none : :hard,
146
+ egress_payload_review: :no_egress
147
+ )
148
+ )
149
+ end
150
+
151
+ # Validate inputs, resolve the path, spawn rg, render the observation.
152
+ # Returns the results, a "no matches" string, or +"Error: ..."+.
153
+ #
154
+ # @param workspace [Workspace]
155
+ # @param pattern [String]
156
+ # @param path [String, nil]
157
+ # @param glob [String, nil]
158
+ # @param case_insensitive [Boolean]
159
+ # @param output_mode [String]
160
+ # @param include_gitignored [Boolean] pass +--no-ignore+ to rg, so
161
+ # +.gitignore+'d files are searched too. Defaults to false.
162
+ # @return [String]
163
+ def self.search(workspace:, pattern:, path:, glob:, case_insensitive:, output_mode:,
164
+ include_gitignored: false)
165
+ return Tool::Result.error('empty pattern.') if pattern.empty?
166
+ unless OUTPUT_MODES.include?(output_mode)
167
+ return Tool::Result.error("output_mode must be one of #{OUTPUT_MODES.join(', ')}, " \
168
+ "got #{output_mode.inspect}.")
169
+ end
170
+
171
+ search_target = '.'
172
+ resolved_root = workspace.project_root
173
+ if path
174
+ resolved = workspace.resolve_for_read(path)
175
+ return Tool::Result.error("path not found: #{path}") unless resolved.exist?
176
+
177
+ resolved_root = resolved
178
+ rel = resolved.relative_path_from(workspace.project_root).to_s
179
+ search_target = rel
180
+ end
181
+
182
+ if (refusal = Utils.oversized_root_refusal(resolved_root, filesystem: workspace.filesystem,
183
+ verb: 'search'))
184
+ return Tool::Result.error(refusal)
185
+ end
186
+
187
+ denied_prefixes = Utils.denied_prefixes(filesystem: workspace.filesystem,
188
+ root: workspace.project_root)
189
+ argv = build_argv(pattern: pattern, glob: glob,
190
+ case_insensitive: case_insensitive,
191
+ output_mode: output_mode, path: search_target,
192
+ include_gitignored: include_gitignored,
193
+ denied_globs: denied_prefixes.flat_map { |rel| ['--glob', "!#{rel}"] })
194
+
195
+ result = Pikuri::Subprocess.spawn(*argv, chdir: workspace.project_root.to_s).wait
196
+ exit_code = result.status.exitstatus
197
+
198
+ case exit_code
199
+ when 0
200
+ format_output(result.output, output_mode: output_mode,
201
+ pattern: pattern, path: path,
202
+ denied_prefixes: denied_prefixes)
203
+ when 1
204
+ no_match_message(pattern: pattern, path: path)
205
+ else
206
+ Tool::Result.error("ripgrep: #{truncate_error(result.output, exit_code)}")
207
+ end
208
+ rescue Filesystem::Error => e
209
+ Tool::Result.error(e.message)
210
+ end
211
+
212
+ # Build the +rg+ argv. Path is always passed (defaults to +.+) — see the
213
+ # class header.
214
+ #
215
+ # @return [Array<String>]
216
+ def self.build_argv(pattern:, glob:, case_insensitive:, output_mode:, path:,
217
+ include_gitignored:, denied_globs: [])
218
+ argv = [
219
+ 'rg',
220
+ '--line-number',
221
+ '--color=never',
222
+ '--no-heading',
223
+ '--with-filename',
224
+ '--hidden',
225
+ "--max-columns=#{MAX_LINE_LENGTH}",
226
+ '--max-columns-preview',
227
+ '--sort=path'
228
+ ]
229
+ argv.concat(denied_globs)
230
+ argv << '--no-ignore' if include_gitignored
231
+ argv << '-i' if case_insensitive
232
+ argv.push('--glob', glob) if glob
233
+ case output_mode
234
+ when 'files_with_matches' then argv << '--files-with-matches'
235
+ when 'count' then argv << '--count-matches'
236
+ end
237
+ argv.push('--', pattern, path)
238
+ argv
239
+ end
240
+ private_class_method :build_argv
241
+
242
+ # Render rg output: strip the +./+ prefix, head-truncate at {MAX_BYTES},
243
+ # append a count footer.
244
+ #
245
+ # @return [Tool::Result] the hits, carrying +"Found 7 matches in 3
246
+ # files"+
247
+ def self.format_output(raw, output_mode:, pattern:, path:, denied_prefixes:)
248
+ # The guarantee, after build_argv's pruning did the cheap 99%. Runs on
249
+ # ./-stripped text so the prefixes are workspace-relative like rg's.
250
+ cleaned = Utils.reject_denied_lines(strip_dot_slash(raw), prefixes: denied_prefixes)
251
+ content, truncation_marker = head_truncate(cleaned)
252
+ stripped = content.chomp
253
+
254
+ return no_match_message(pattern: pattern, path: path) if stripped.empty?
255
+
256
+ phrase = match_phrase(stripped, output_mode)
257
+ Tool::Result.new(content: [stripped, '', "Found #{phrase}." + truncation_marker].join("\n"),
258
+ summary: "Found #{phrase}")
259
+ end
260
+ private_class_method :format_output
261
+
262
+ # Strip leading +./+ from each line — rg emits it when invoked with +.+ as
263
+ # the search path; we want clean workspace-relative paths.
264
+ #
265
+ # @return [String]
266
+ def self.strip_dot_slash(raw)
267
+ raw.gsub(/^\.\//, '')
268
+ end
269
+ private_class_method :strip_dot_slash
270
+
271
+ # Head-truncate +raw+ to {MAX_BYTES}. Returns the content and a marker
272
+ # (empty if no truncation).
273
+ #
274
+ # @return [Array(String, String)]
275
+ def self.head_truncate(raw)
276
+ Utils.head_truncate(raw, max_bytes: MAX_BYTES, hint: 'refine pattern or path')
277
+ end
278
+ private_class_method :head_truncate
279
+
280
+ # Head-truncate an rg error blob to {MAX_BYTES}. rg writes one diagnostic
281
+ # per unreadable path (broken symlinks, permission denials — a search
282
+ # escaping into +~/.local/share/docker+ overlays), so on exit 2 the merged
283
+ # stderr can run to hundreds of KB and overflow context; this gives the
284
+ # error path the same ceiling as the success path.
285
+ #
286
+ # @param raw [String] rg's merged stdout+stderr
287
+ # @param exit_code [Integer] for the empty-output fallback
288
+ # @return [String]
289
+ def self.truncate_error(raw, exit_code)
290
+ stderr = raw.strip
291
+ return "exited #{exit_code}" if stderr.empty?
292
+
293
+ content, marker = head_truncate(stderr)
294
+ content + marker
295
+ end
296
+ private_class_method :truncate_error
297
+
298
+ # The counted phrase the observation's footer and the display summary are
299
+ # both built from — +"7 matches in 3 files"+, +"3 files"+ in
300
+ # +files_with_matches+ mode.
301
+ #
302
+ # @return [String]
303
+ def self.match_phrase(content, output_mode)
304
+ lines = content.split("\n").reject(&:empty?)
305
+ case output_mode
306
+ when 'content'
307
+ files = lines.map { |l| l.split(':', 2).first }.uniq
308
+ "#{Pikuri::Tool.pluralize(lines.size, 'match', 'matches')} in " \
309
+ "#{Pikuri::Tool.pluralize(files.size, 'file', 'files')}"
310
+ when 'files_with_matches'
311
+ Pikuri::Tool.pluralize(lines.size, 'file', 'files')
312
+ when 'count'
313
+ total = lines.sum { |l| Integer(l.split(':').last) }
314
+ "#{Pikuri::Tool.pluralize(total, 'match', 'matches')} in " \
315
+ "#{Pikuri::Tool.pluralize(lines.size, 'file', 'files')}"
316
+ end
317
+ end
318
+ private_class_method :match_phrase
319
+
320
+ # @return [Tool::Result] the "nothing matched" observation, carrying
321
+ # +"Found 0 matches"+
322
+ def self.no_match_message(pattern:, path:)
323
+ base = "No matches for pattern '#{pattern}'"
324
+ base += " in #{path}" if path
325
+ Tool::Result.new(content: "#{base}.", summary: 'Found 0 matches')
326
+ end
327
+ private_class_method :no_match_message
328
+
329
+ # Verify +rg+ is on +PATH+ (via {Pikuri::Subprocess.spawn}, honoring the
330
+ # subprocess seam). Missing → +Errno::ENOENT+; installed → exit 0.
331
+ #
332
+ # @return [void]
333
+ # @raise [RuntimeError] if rg is missing
334
+ def self.check_binaries!
335
+ result = Pikuri::Subprocess.spawn('rg', '--version', chdir: '/').wait
336
+ return if result.status.success?
337
+
338
+ raise install_hint
339
+ rescue Errno::ENOENT
340
+ raise install_hint
341
+ end
342
+ private_class_method :check_binaries!
343
+
344
+ # @return [String]
345
+ def self.install_hint
346
+ "Grep requires 'rg' (ripgrep) on PATH; install via your " \
347
+ "distro's package manager (e.g. 'apt install ripgrep')."
348
+ end
349
+ private_class_method :install_hint
350
+ end
351
+ end
352
+ end
353
+ end