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.
@@ -1,350 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- module Pikuri
4
- module Workspace
5
- # The +grep+ tool — content search across the workspace via
6
- # +ripgrep+. Instantiating +Grep.new(workspace: ws)+ produces a
7
- # tool whose {Pikuri::Tool#to_ruby_llm_tool} wiring is identical to
8
- # any bundled tool's. Same shape as {Read} (workspace captured by
9
- # the +execute+ closure, no confirmer — search is read-only).
10
- #
11
- # == ripgrep dependency
12
- #
13
- # Hard dependency: {.check_binaries!} runs in +initialize+ and raises
14
- # if +rg+ isn't on +PATH+. Mirrors {Pikuri::Code::Bash}'s posture for
15
- # +bash+/+timeout+. We don't ship a Ruby fallback — replicating
16
- # rg's Rust-regex dialect, glob handling, and +.gitignore+ parsing
17
- # is a research-loop dead end. Failure message includes the install
18
- # hint.
19
- #
20
- # == Argv
21
- #
22
- # rg --line-number --color=never --no-heading --with-filename \
23
- # --hidden --max-columns=2000 --max-columns-preview \
24
- # --sort=path \
25
- # [-i] [--glob <g>] [--files-with-matches|--count-matches] \
26
- # -- <pattern> <relative-path-or-dot>
27
- #
28
- # * +--no-heading+ + +--with-filename+ → flat +path:line:content+ rows
29
- # regardless of whether the search target is a directory or a single
30
- # file (rg defaults to suppressing the filename for single-file
31
- # searches — we force it on for output consistency).
32
- # * +--hidden+ → search dotfiles (still respects +.gitignore+).
33
- # * +--max-columns=2000 --max-columns-preview+ → rg truncates lines
34
- # longer than {MAX_LINE_LENGTH} bytes server-side and appends a
35
- # preview marker, sparing us per-line truncation.
36
- # * +--sort=path+ → deterministic output (single-threaded; fine for
37
- # typical repos under ~10k files). Makes specs assertable and gives
38
- # the model a stable order to scan.
39
- # * Subprocess runs with +chdir: workspace.project_root+ and is *always* given
40
- # an explicit path argument. {Pikuri::Subprocess.spawn} uses
41
- # +popen2e+ which gives the child a piped (non-tty) stdin; rg's
42
- # default heuristic on no-path-arg-with-piped-stdin is to search
43
- # stdin (which we then close — yielding zero matches). Passing the
44
- # path argument explicitly bypasses the heuristic. Output paths
45
- # come back as +./...+ when the path is +.+; the leading +./+ is
46
- # stripped post-rg so the model sees clean workspace-relative paths.
47
- #
48
- # == Output modes
49
- #
50
- # * +content+ (default) — +path:line:content+ rows.
51
- # * +files_with_matches+ — just file paths, one per line.
52
- # * +count+ — +path:count+ per file.
53
- #
54
- # Use +files_with_matches+ to scope a broad search cheaply before
55
- # paying tokens for +content+.
56
- #
57
- # == Truncation
58
- #
59
- # Total output is head-truncated to {MAX_BYTES} (head-only — grep
60
- # tails usually carry less signal than the first matches; opposite
61
- # bias from {Pikuri::Code::Bash}). Cut at the last line boundary, with a
62
- # marker reporting omitted bytes and the original total so the model
63
- # knows how much it missed.
64
- #
65
- # == Exit codes
66
- #
67
- # * +0+ → matches; format with footer.
68
- # * +1+ → no matches; return +"No matches for pattern '...'"+.
69
- # * +2+ → rg error (bad regex, missing path); return +"Error: ripgrep: ..."+.
70
- #
71
- # == Refusals
72
- #
73
- # All returned as +"Error: ..."+ observations:
74
- #
75
- # * Empty +pattern+ → fast reject.
76
- # * Unknown +output_mode+ → enum error listing valid values.
77
- # * Path outside the workspace → caught from {Filesystem::Error}.
78
- # * Nonexistent path → +"Error: path not found: <path>"+.
79
- class Grep < Pikuri::Tool
80
- # @return [Integer] hard byte cap on combined rg output. Same value
81
- # as {Read::MAX_BYTES} so the two file-touching tools share
82
- # a budget shape.
83
- MAX_BYTES = 50 * 1024
84
-
85
- # @return [String] human-readable form of {MAX_BYTES} for the
86
- # truncation marker.
87
- MAX_BYTES_LABEL = "#{MAX_BYTES / 1024} KB"
88
-
89
- # @return [Integer] per-line cap passed to rg's +--max-columns+.
90
- # Long lines are truncated server-side with a preview marker.
91
- MAX_LINE_LENGTH = 2000
92
-
93
- # @return [Array<String>] valid +output_mode+ values.
94
- OUTPUT_MODES = %w[content files_with_matches count].freeze
95
-
96
- # @return [String] default +output_mode+.
97
- DEFAULT_OUTPUT_MODE = 'content'
98
-
99
- # Description shown to the LLM. opencode-shape (summary + +Usage:+
100
- # bullets). Per-parameter constraints live in parameter
101
- # descriptions.
102
- #
103
- # @return [String]
104
- DESCRIPTION = <<~DESC
105
- Search file contents for a regex pattern across the workspace.
106
-
107
- Usage:
108
- - Wraps `ripgrep` — regex syntax is rg's Rust-regex dialect (mostly PCRE-compatible; no lookbehind).
109
- - Default search root is the workspace root; pass `path` to narrow to a file or subdirectory.
110
- - Respects `.gitignore` — for unfiltered search use bash `rg --no-ignore <pattern>`.
111
- - Use `glob` to filter by filename, e.g. `"*.rb"` or `"src/**/*.{ts,tsx}"`.
112
- - `output_mode` controls verbosity: `content` (default, file:line:text), `files_with_matches` (paths only), `count` (matches per file).
113
- - Use `files_with_matches` first to scope a broad search, then `content` (or `read`) to investigate — saves tokens.
114
- - Output is truncated to #{MAX_BYTES_LABEL}; refine the pattern or narrow `path` if the response ends in a truncation marker.
115
- - Long lines are truncated to #{MAX_LINE_LENGTH} chars with a preview marker; use `read` to see full lines.
116
- DESC
117
-
118
- # @param workspace [Filesystem] captured for path resolution
119
- # and as +chdir+ for rg. All path arguments route through
120
- # +workspace.resolve_for_read+.
121
- # @raise [RuntimeError] if +rg+ isn't on +PATH+; fail-loud at
122
- # construction rather than the first tool call.
123
- # @return [Grep]
124
- def initialize(workspace:)
125
- Grep.send(:check_binaries!)
126
- super(
127
- name: 'grep',
128
- description: DESCRIPTION,
129
- parameters: Parameters.build { |p|
130
- p.required_string :pattern,
131
- 'Regex pattern to search for (rg Rust-regex ' \
132
- 'dialect), e.g. "def\s+\w+" or "TODO".'
133
- p.optional_string :path,
134
- 'File or directory to search. Relative paths ' \
135
- 'resolve against the workspace root. Defaults ' \
136
- 'to the workspace root, e.g. "lib/" or "lib/foo.rb".'
137
- p.optional_string :glob,
138
- 'Filename glob to filter files, e.g. "*.rb" ' \
139
- 'or "src/**/*.{ts,tsx}".'
140
- p.optional_boolean :case_insensitive,
141
- 'Match case-insensitively. Defaults to false, e.g. true.'
142
- p.optional_string :output_mode,
143
- "One of #{OUTPUT_MODES.join(', ')}. Defaults to " \
144
- "#{DEFAULT_OUTPUT_MODE}, e.g. \"files_with_matches\"."
145
- },
146
- execute: lambda { |pattern:, path: nil, glob: nil,
147
- case_insensitive: false, output_mode: DEFAULT_OUTPUT_MODE|
148
- Grep.search(workspace: workspace, pattern: pattern, path: path,
149
- glob: glob, case_insensitive: case_insensitive,
150
- output_mode: output_mode)
151
- }
152
- )
153
- end
154
-
155
- # Produce a new {Grep} bound to +workspace+. Used by
156
- # {Pikuri::SubAgent::SubAgentTool} when a persona supplies a
157
- # +workspace_factory:+ — the parent's instance is rebuilt for
158
- # the sub-agent's fresh workspace so paths resolve against the
159
- # right root.
160
- #
161
- # @param workspace [Filesystem]
162
- # @return [Grep]
163
- def with_workspace(workspace)
164
- self.class.new(workspace: workspace)
165
- end
166
-
167
- # Validate inputs, resolve the path against the workspace, spawn
168
- # rg, and render the observation. Returns either the formatted
169
- # results, a "no matches" string, or +"Error: ..."+.
170
- #
171
- # @param workspace [Filesystem]
172
- # @param pattern [String]
173
- # @param path [String, nil]
174
- # @param glob [String, nil]
175
- # @param case_insensitive [Boolean]
176
- # @param output_mode [String]
177
- # @return [String]
178
- def self.search(workspace:, pattern:, path:, glob:, case_insensitive:, output_mode:)
179
- return 'Error: empty pattern.' if pattern.empty?
180
- unless OUTPUT_MODES.include?(output_mode)
181
- return "Error: output_mode must be one of #{OUTPUT_MODES.join(', ')}, " \
182
- "got #{output_mode.inspect}."
183
- end
184
-
185
- search_target = '.'
186
- if path
187
- resolved = workspace.resolve_for_read(path)
188
- return "Error: path not found: #{path}" unless resolved.exist?
189
-
190
- rel = resolved.relative_path_from(workspace.project_root).to_s
191
- search_target = rel
192
- end
193
-
194
- argv = build_argv(pattern: pattern, glob: glob,
195
- case_insensitive: case_insensitive,
196
- output_mode: output_mode, path: search_target)
197
-
198
- result = Pikuri::Subprocess.spawn(*argv, chdir: workspace.project_root.to_s).wait
199
- exit_code = result.status.exitstatus
200
-
201
- case exit_code
202
- when 0
203
- format_output(result.output, output_mode: output_mode,
204
- pattern: pattern, path: path)
205
- when 1
206
- no_match_message(pattern: pattern, path: path)
207
- else
208
- stderr = result.output.strip
209
- stderr = "exited #{exit_code}" if stderr.empty?
210
- "Error: ripgrep: #{stderr}"
211
- end
212
- rescue Filesystem::Error => e
213
- "Error: #{e.message}"
214
- end
215
-
216
- # Build the +rg+ argv. Path is always passed (defaults to +.+) —
217
- # see the class header for why.
218
- #
219
- # @return [Array<String>]
220
- def self.build_argv(pattern:, glob:, case_insensitive:, output_mode:, path:)
221
- argv = [
222
- 'rg',
223
- '--line-number',
224
- '--color=never',
225
- '--no-heading',
226
- '--with-filename',
227
- '--hidden',
228
- "--max-columns=#{MAX_LINE_LENGTH}",
229
- '--max-columns-preview',
230
- '--sort=path'
231
- ]
232
- argv << '-i' if case_insensitive
233
- argv.push('--glob', glob) if glob
234
- case output_mode
235
- when 'files_with_matches' then argv << '--files-with-matches'
236
- when 'count' then argv << '--count-matches'
237
- end
238
- argv.push('--', pattern, path)
239
- argv
240
- end
241
- private_class_method :build_argv
242
-
243
- # Render rg output: strip the +./+ prefix rg adds when path is
244
- # +.+, head-truncate at {MAX_BYTES}, append a footer summarizing
245
- # the result count.
246
- #
247
- # @return [String]
248
- def self.format_output(raw, output_mode:, pattern:, path:)
249
- cleaned = strip_dot_slash(raw)
250
- content, truncation_marker = head_truncate(cleaned)
251
- stripped = content.chomp
252
-
253
- return no_match_message(pattern: pattern, path: path) if stripped.empty?
254
-
255
- footer = build_footer(stripped, output_mode)
256
- [stripped, '', footer + truncation_marker].join("\n")
257
- end
258
- private_class_method :format_output
259
-
260
- # Strip leading +./+ from each line of rg output. rg emits this
261
- # prefix when invoked with +.+ as the search path; we want clean
262
- # workspace-relative paths regardless of whether the user passed a
263
- # path or we defaulted to +.+.
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}, cutting at the last newline
272
- # boundary so the final row is never partial. Returns the truncated
273
- # content and a marker String (empty if no truncation).
274
- #
275
- # @return [Array(String, String)]
276
- def self.head_truncate(raw)
277
- total = raw.bytesize
278
- return [raw, ''] if total <= MAX_BYTES
279
-
280
- head = raw.byteslice(0, MAX_BYTES)
281
- last_nl = head.rindex("\n")
282
- head = head.byteslice(0, last_nl) if last_nl
283
- omitted = total - head.bytesize
284
- marker = "\n\n... [#{omitted} bytes omitted; total was #{total} bytes; " \
285
- 'refine pattern or path] ...'
286
- [head, marker]
287
- end
288
- private_class_method :head_truncate
289
-
290
- # Compose a one-line footer summarizing the result. Format depends
291
- # on +output_mode+; counts derive from rg's text output.
292
- #
293
- # @return [String]
294
- def self.build_footer(content, output_mode)
295
- lines = content.split("\n").reject(&:empty?)
296
- case output_mode
297
- when 'content'
298
- files = lines.map { |l| l.split(':', 2).first }.uniq
299
- "Found #{pluralize(lines.size, 'match', 'matches')} in " \
300
- "#{pluralize(files.size, 'file', 'files')}."
301
- when 'files_with_matches'
302
- "Found #{pluralize(lines.size, 'file', 'files')}."
303
- when 'count'
304
- total = lines.sum { |l| Integer(l.split(':').last) }
305
- "Found #{pluralize(total, 'match', 'matches')} in " \
306
- "#{pluralize(lines.size, 'file', 'files')}."
307
- end
308
- end
309
- private_class_method :build_footer
310
-
311
- # @return [String] +"1 match"+ / +"2 matches"+
312
- def self.pluralize(n, sing, plural)
313
- "#{n} #{n == 1 ? sing : plural}"
314
- end
315
- private_class_method :pluralize
316
-
317
- # @return [String]
318
- def self.no_match_message(pattern:, path:)
319
- base = "No matches for pattern '#{pattern}'"
320
- base += " in #{path}" if path
321
- "#{base}."
322
- end
323
- private_class_method :no_match_message
324
-
325
- # Verify +rg+ is reachable on +PATH+. Routed through
326
- # {Pikuri::Subprocess.spawn} to honor the subprocess seam.
327
- # rg missing surfaces as +Errno::ENOENT+; an installed rg returns
328
- # exit 0 from +--version+.
329
- #
330
- # @return [void]
331
- # @raise [RuntimeError] if rg is missing
332
- def self.check_binaries!
333
- result = Pikuri::Subprocess.spawn('rg', '--version', chdir: '/').wait
334
- return if result.status.success?
335
-
336
- raise install_hint
337
- rescue Errno::ENOENT
338
- raise install_hint
339
- end
340
- private_class_method :check_binaries!
341
-
342
- # @return [String]
343
- def self.install_hint
344
- "Grep requires 'rg' (ripgrep) on PATH; install via your " \
345
- "distro's package manager (e.g. 'apt install ripgrep')."
346
- end
347
- private_class_method :install_hint
348
- end
349
- end
350
- end
@@ -1,102 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- require 'pathname'
4
-
5
- module Pikuri
6
- module Workspace
7
- # Climb from a working directory toward the project root, looking
8
- # for a VCS marker (+.git+ / +.hg+ / +.svn+). Used by host binaries
9
- # to decide what to pass as the {Filesystem} +project_root:+ — the
10
- # writable containment ceiling and (under the +Bubblewrap+ sandbox)
11
- # the bind-mount root, so commands like +git+ and +make+ can climb
12
- # inside the sandbox to find +<repo>/.git+ / +<repo>/Makefile+.
13
- #
14
- # == Why VCS-only markers
15
- #
16
- # An earlier draft considered build-system fallbacks
17
- # (+Gemfile+, +Rakefile+, +pyproject.toml+, +package.json+,
18
- # +Cargo.toml+, +go.mod+, +pom.xml+, +build.gradle+,
19
- # +build.gradle.kts+). They were rejected because they are not
20
- # reliable project-root markers in multi-module setups: a Gradle
21
- # subproject has its own +build.gradle.kts+, a Maven module has
22
- # its own +pom.xml+, a yarn-workspaces package has its own
23
- # +package.json+. Climbing for those lands on the nearest subtree
24
- # root, not the actual project root — and the project_root choice
25
- # decides what the sandbox bind-mounts. Wrong project_root → +git+ can't
26
- # see the real +.git+ inside the sandbox. The VCS markers don't
27
- # have this problem: git/hg/svn put their metadata only at the
28
- # actual root (or, for git submodules, at the submodule root,
29
- # which is the user's intended project boundary when they cd'd
30
- # into the submodule).
31
- #
32
- # If no VCS marker is found within the safe-climb bounds (see
33
- # below), {.find} returns +nil+ and the caller falls back to
34
- # using the launch +cwd+ as the project_root. The LLM loses visibility to
35
- # sibling code outside +cwd+ in that case; the workaround is to
36
- # +git init+ or invoke pikuri from the actual project root.
37
- #
38
- # == Safety bounds
39
- #
40
- # The climb refuses to enter the user's home directory or any
41
- # system root ({DENIED_CLIMB_ROOTS}). Reaching either is treated as
42
- # "I've left the project tree" and the climb stops. The starting
43
- # +cwd+ is always considered, even if it happens to be a banned
44
- # directory — the user explicitly invoked there. Only ancestors
45
- # are gated.
46
- #
47
- # == Priority
48
- #
49
- # All +markers+ are checked at each ancestor before climbing to
50
- # the next, so the *nearest* VCS marker wins regardless of type.
51
- # In practice +.git+/+.hg+/+.svn+ never appear at different levels
52
- # of the same tree (hg-git users have them at the same level), so
53
- # this matches user intuition: "the closest project root, however
54
- # it's marked."
55
- module ProjectRoot
56
- # Climb-up boundary. Overlaps with {Filesystem::DENIED_PROJECT_ROOTS}
57
- # but kept separate: the two have different semantics
58
- # (climb-up boundary vs. project_root rejection) and may drift
59
- # apart.
60
- DENIED_CLIMB_ROOTS = %w[
61
- / /etc /var /proc /sys /dev /boot /root
62
- /usr /opt /lib /lib64 /bin /sbin /tmp
63
- ].map { |p| Pathname.new(p) }.freeze
64
-
65
- # VCS metadata directories/files. +.git+ is by far the common
66
- # case; +.hg+ and +.svn+ are included for the rare users on
67
- # those systems. +File.exist?+ matches both directories
68
- # (+.git+ in a normal checkout) and regular files (+.git+ in a
69
- # git worktree / submodule), so both work without special
70
- # handling.
71
- VCS_MARKERS = %w[.git .hg .svn].freeze
72
-
73
- # Find the nearest ancestor of +cwd+ containing any of the
74
- # given VCS +markers+. See the class header for the safety
75
- # bounds and the priority rule.
76
- #
77
- # @param cwd [String, Pathname] starting directory; +realpath+'d
78
- # before climbing so symlinked checkouts don't bounce out of
79
- # the project tree.
80
- # @param markers [Array<String>] VCS marker names to look for.
81
- # Defaults to {VCS_MARKERS}.
82
- # @return [Pathname, nil] the matching ancestor, or +nil+ if no
83
- # marker was found within the safe-climb bounds — caller
84
- # should fall back to its own default (typically the launch
85
- # +cwd+).
86
- def self.find(cwd:, markers: VCS_MARKERS)
87
- current = Pathname.new(cwd).realpath
88
- home = Pathname.new(Dir.home).realpath
89
- loop do
90
- return current if markers.any? { |m| current.join(m).exist? }
91
-
92
- parent = current.parent
93
- return nil if parent == current # at the filesystem root
94
- return nil if parent == home # crossing into $HOME
95
- return nil if DENIED_CLIMB_ROOTS.include?(parent)
96
-
97
- current = parent
98
- end
99
- end
100
- end
101
- end
102
- end