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.
@@ -3,16 +3,20 @@
3
3
  require 'pikuri-core'
4
4
 
5
5
  # Entry file for the pikuri-workspace gem. After
6
- # +require 'pikuri-workspace'+, +Pikuri::Workspace::Filesystem+,
7
- # +Pikuri::Workspace::Confirmer+, and the five file tools (+Read+,
8
- # +Write+, +Edit+, +Grep+, +Glob+) are all defined under the
6
+ # +require 'pikuri-workspace'+, +Pikuri::Workspace::Filesystem+, the
7
+ # +Pikuri::Workspace::Workspace+ composite (Filesystem + read record),
8
+ # +Pikuri::Workspace::Confirmer+, and the file tools (+Read+, +Write+,
9
+ # +Edit+, +Grep+, +Glob+, +FileList+) are all defined under the
9
10
  # +Pikuri::Workspace+ namespace.
10
11
  #
11
12
  # The Zeitwerk loader is mounted plainly at this gem's +lib/+ root —
12
13
  # Zeitwerk infers +Pikuri+ from pikuri-core and auto-vivifies
13
14
  # +Pikuri::Workspace+ as a module from the +pikuri/workspace/+
14
15
  # directory, so individual files like +lib/pikuri/workspace/read.rb+
15
- # autoload as +Pikuri::Workspace::Read+.
16
+ # autoload as +Pikuri::Workspace::Read+. Its +prompts/+ joins
17
+ # +Pikuri::PROMPT_DIRS+ for +bin/pikuri-files+'s prompt.
18
+ Pikuri::PROMPT_DIRS << File.expand_path('../prompts', __dir__)
19
+
16
20
  module Pikuri
17
21
  module Workspace
18
22
  LOADER = Zeitwerk::Loader.new
@@ -21,11 +25,5 @@ module Pikuri
21
25
  LOADER.ignore(File.expand_path('pikuri-workspace.rb', __dir__))
22
26
  LOADER.setup
23
27
  LOADER.eager_load
24
-
25
- # Reap +~/.cache/pikuri/workspace-*+ leftovers from sessions
26
- # killed before the {Pikuri::Finalizers} removal could fire.
27
- # Best-effort; runs once at gem load. See
28
- # {Filesystem.sweep_stale_internal_temps!}.
29
- Filesystem.sweep_stale_internal_temps!
30
28
  end
31
29
  end
@@ -0,0 +1,6 @@
1
+ You are an assistant working in one folder of the user's files. You can look around it, read what's there, and change or create files in it. Nothing outside the folder is reachable.
2
+
3
+ How to work:
4
+ - Look before you change: read a file before you edit it, and check what's already in the folder before you create something new.
5
+ - Change only what the user asked for. Prefer a small edit to rewriting a whole file.
6
+ - Every change is shown to the user before it is saved. Say briefly what you're about to change and why, so they can judge it.
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: pikuri-workspace
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.0.7
4
+ version: 0.2.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Martin Vysny
@@ -15,19 +15,33 @@ dependencies:
15
15
  requirements:
16
16
  - - '='
17
17
  - !ruby/object:Gem::Version
18
- version: 0.0.7
18
+ version: 0.2.0
19
19
  type: :runtime
20
20
  prerelease: false
21
21
  version_requirements: !ruby/object:Gem::Requirement
22
22
  requirements:
23
23
  - - '='
24
24
  - !ruby/object:Gem::Version
25
- version: 0.0.7
25
+ version: 0.2.0
26
+ - !ruby/object:Gem::Dependency
27
+ name: reline
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - "~>"
31
+ - !ruby/object:Gem::Version
32
+ version: '0.6'
33
+ type: :runtime
34
+ prerelease: false
35
+ version_requirements: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - "~>"
38
+ - !ruby/object:Gem::Version
39
+ version: '0.6'
26
40
  description: |
27
41
  pikuri-workspace adds "operate on a directory tree" to pikuri-core
28
42
  agents: the +Pikuri::Workspace::Filesystem+ class that scopes
29
43
  filesystem access to an anchor + explicit readable / writable
30
- prefix lists (with optional ephemeral temp playground), the
44
+ prefix lists, the
31
45
  +Pikuri::Workspace::Confirmer+ seam (+AUTO_APPROVE+ + +TERMINAL+)
32
46
  for user-state mutations, and five tools wired to those seams:
33
47
  +Pikuri::Workspace::Read+, +Pikuri::Workspace::Write+,
@@ -43,20 +57,27 @@ files:
43
57
  - README.md
44
58
  - lib/pikuri-workspace.rb
45
59
  - lib/pikuri/workspace/confirmer.rb
60
+ - lib/pikuri/workspace/confirmer/terminal.rb
46
61
  - lib/pikuri/workspace/edit.rb
62
+ - lib/pikuri/workspace/extension.rb
63
+ - lib/pikuri/workspace/file_list.rb
47
64
  - lib/pikuri/workspace/filesystem.rb
48
- - lib/pikuri/workspace/glob.rb
49
- - lib/pikuri/workspace/grep.rb
50
- - lib/pikuri/workspace/project_root.rb
65
+ - lib/pikuri/workspace/listing.rb
51
66
  - lib/pikuri/workspace/read.rb
67
+ - lib/pikuri/workspace/search/glob.rb
68
+ - lib/pikuri/workspace/search/grep.rb
69
+ - lib/pikuri/workspace/search/utils.rb
70
+ - lib/pikuri/workspace/workspace.rb
52
71
  - lib/pikuri/workspace/write.rb
53
- homepage: https://codeberg.org/mvysny/pikuri
72
+ - lib/pikuri/workspace/write_gate.rb
73
+ - prompts/pikuri-files.txt
74
+ homepage: https://github.com/mvysny/pikuri
54
75
  licenses:
55
76
  - MIT
56
77
  metadata:
57
- source_code_uri: https://codeberg.org/mvysny/pikuri/src/branch/master
58
- changelog_uri: https://codeberg.org/mvysny/pikuri/src/branch/master/CHANGELOG.md
59
- bug_tracker_uri: https://codeberg.org/mvysny/pikuri/issues
78
+ source_code_uri: https://github.com/mvysny/pikuri/tree/master
79
+ changelog_uri: https://github.com/mvysny/pikuri/blob/master/CHANGELOG.md
80
+ bug_tracker_uri: https://github.com/mvysny/pikuri/issues
60
81
  rubygems_mfa_required: 'true'
61
82
  rdoc_options: []
62
83
  require_paths:
@@ -1,322 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- module Pikuri
4
- module Workspace
5
- # The +glob+ tool — list files matching a glob pattern via
6
- # +rg --files+, sorted by modification time (newest first).
7
- # Instantiating +Glob.new(workspace: ws)+ produces a tool
8
- # whose {Pikuri::Tool#to_ruby_llm_tool} wiring is identical to any
9
- # bundled tool's. Same shape as {Grep} (workspace captured by the
10
- # +execute+ closure, no confirmer — read-only).
11
- #
12
- # == Why a separate tool from Grep
13
- #
14
- # The unique capability is *mtime-descending sort* — "what's been
15
- # touched recently" is a common navigation move and Grep can't
16
- # express it. The rest (filter by name, default to listing all
17
- # matching files) is theoretically reachable through Grep with
18
- # +pattern="."+, but Glob avoids that hack and keeps Read / Grep /
19
- # Glob as three clean roles: read one file, search content, list
20
- # files by name.
21
- #
22
- # == ripgrep dependency
23
- #
24
- # Hard dependency: {.check_binaries!} runs in +initialize+ and
25
- # raises if +rg+ isn't on +PATH+. Each tool owns its own probe so
26
- # construction order doesn't matter — Glob doesn't lean on Grep's
27
- # check.
28
- #
29
- # == Argv & filter pipeline
30
- #
31
- # rg --files --color=never --hidden --glob '!.git/*' \
32
- # -- <relative-path-or-dot>
33
- # # …then filter the result list in Ruby with File.fnmatch?
34
- #
35
- # Why not pass the user pattern as +--glob+ to rg? Because rg's
36
- # +--glob+ documentation says *"This always overrides any other
37
- # ignore logic"* — so +--glob '**/*.rb'+ would re-include
38
- # +.gitignore+'d Ruby files, breaking our gitignore-respect
39
- # promise. We let rg produce the full gitignore-respecting file
40
- # list and filter to the user's pattern in Ruby with
41
- # +File.fnmatch?(pattern, p, FNM_PATHNAME | FNM_EXTGLOB |
42
- # FNM_DOTMATCH)+. The three flags together cover the common rg
43
- # glob cases: +**+ recursion (+FNM_PATHNAME+), +{a,b}+ alternation
44
- # (+FNM_EXTGLOB+), and dotfile inclusion (+FNM_DOTMATCH+, matching
45
- # rg's +--hidden+ behavior). The +.git/+ exclusion stays on the rg
46
- # side so its contents never even reach the Ruby filter.
47
- #
48
- # * +--hidden+ → search dotfiles (still respects +.gitignore+).
49
- # * No +--sort+ flag: we re-sort by mtime in Ruby on the way out.
50
- # * Output paths come back as +./...+ when the search path is +.+;
51
- # the leading +./+ is stripped post-rg so the model sees clean
52
- # workspace-relative paths.
53
- #
54
- # == Sort
55
- #
56
- # mtime-descending in Ruby after rg returns, with path-ascending
57
- # as a tiebreaker for files with equal mtimes (the common case in
58
- # fresh checkouts). Cost: one +stat+ per result. Broad patterns
59
- # can make this expensive, but in practice rg's +.gitignore+ filter
60
- # keeps result sets bounded; if real friction shows up later we can
61
- # cap pre-sort.
62
- #
63
- # == Truncation
64
- #
65
- # Total output head-truncated to {MAX_BYTES} *after* mtime sort, so
66
- # the kept rows are the newest. Matches {Grep}'s budget and
67
- # head-bias.
68
- #
69
- # == Exit codes
70
- #
71
- # * +0+ → at least one file; format with footer.
72
- # * +1+ → no files; return +"No files match pattern '...'"+.
73
- # * +2+ → rg error (bad path, bad glob); return
74
- # +"Error: ripgrep: ..."+.
75
- #
76
- # == Refusals
77
- #
78
- # All returned as +"Error: ..."+ observations:
79
- #
80
- # * Empty +pattern+ → fast reject.
81
- # * +path+ is a regular file → fast reject pointing at the +read+
82
- # tool.
83
- # * +path+ not found → +"Error: path not found: <path>"+.
84
- # * +path+ outside the workspace → caught from
85
- # {Filesystem::Error}.
86
- class Glob < Pikuri::Tool
87
- # @return [Integer] hard byte cap on combined rg output. Same
88
- # value as {Grep::MAX_BYTES} so the two file-touching
89
- # tools share a budget shape. Re-declared here rather than
90
- # referenced cross-file because Zeitwerk's eager-load order
91
- # isn't guaranteed between siblings.
92
- MAX_BYTES = 50 * 1024
93
-
94
- # @return [String] human-readable form of {MAX_BYTES} for the
95
- # truncation marker.
96
- MAX_BYTES_LABEL = "#{MAX_BYTES / 1024} KB"
97
-
98
- # Description shown to the LLM. opencode-shape (summary +
99
- # +Usage:+ bullets). Per-parameter constraints live in parameter
100
- # descriptions.
101
- #
102
- # @return [String]
103
- DESCRIPTION = <<~DESC
104
- List files matching a glob pattern, sorted by modification time (newest first).
105
-
106
- Usage:
107
- - `.gitignore` is respected; for unfiltered listing use bash `rg --no-ignore --files -g <pattern>`.
108
- - Glob syntax: `**` matches any number of directories, `*` matches any filename chars (not `/`), `{a,b}` is alternation.
109
- - Default search root is the workspace root; pass `path` to narrow to a subdirectory.
110
- - Use `glob` to find files by name; use `grep` to find files by content.
111
- - Output is sorted by mtime descending — recently-touched files come first, so broad patterns still surface relevant files near the top.
112
- - Output is truncated to #{MAX_BYTES_LABEL}; refine the pattern or narrow `path` if the response ends in a truncation marker.
113
- DESC
114
-
115
- # @param workspace [Filesystem] captured for path resolution
116
- # and as +chdir+ for rg. All path arguments route through
117
- # +workspace.resolve_for_read+.
118
- # @raise [RuntimeError] if +rg+ isn't on +PATH+; fail-loud at
119
- # construction rather than the first tool call.
120
- # @return [Glob]
121
- def initialize(workspace:)
122
- Glob.send(:check_binaries!)
123
- super(
124
- name: 'glob',
125
- description: DESCRIPTION,
126
- parameters: Parameters.build { |p|
127
- p.required_string :pattern,
128
- 'Glob pattern (** matches any number of ' \
129
- 'directories; {a,b} alternation), e.g. ' \
130
- '"**/*.rb" or "lib/**/*_spec.rb".'
131
- p.optional_string :path,
132
- 'Directory to search in. Relative paths resolve ' \
133
- 'against the workspace root. Defaults to the ' \
134
- 'workspace root, e.g. "lib/" or "spec/".'
135
- },
136
- execute: lambda { |pattern:, path: nil|
137
- Glob.search(workspace: workspace, pattern: pattern, path: path)
138
- }
139
- )
140
- end
141
-
142
- # Produce a new {Glob} bound to +workspace+. Used by
143
- # {Pikuri::SubAgent::SubAgentTool} when a persona supplies a
144
- # +workspace_factory:+ — the parent's instance is rebuilt for
145
- # the sub-agent's fresh workspace so paths resolve against the
146
- # right root.
147
- #
148
- # @param workspace [Filesystem]
149
- # @return [Glob]
150
- def with_workspace(workspace)
151
- self.class.new(workspace: workspace)
152
- end
153
-
154
- # Validate inputs, resolve the path against the workspace, spawn
155
- # rg, mtime-sort, head-truncate, render. Returns either the
156
- # formatted listing, a "no files match" message, or
157
- # +"Error: ..."+.
158
- #
159
- # @param workspace [Filesystem]
160
- # @param pattern [String]
161
- # @param path [String, nil]
162
- # @return [String]
163
- def self.search(workspace:, pattern:, path:)
164
- return 'Error: empty pattern.' if pattern.empty?
165
-
166
- search_target = '.'
167
- if path
168
- resolved = workspace.resolve_for_read(path)
169
- return "Error: path not found: #{path}" unless resolved.exist?
170
- if resolved.file?
171
- return "Error: #{path} is a file, not a directory; use the read tool to view it."
172
- end
173
-
174
- rel = resolved.relative_path_from(workspace.project_root).to_s
175
- search_target = rel
176
- end
177
-
178
- argv = build_argv(path: search_target)
179
- result = Pikuri::Subprocess.spawn(*argv, chdir: workspace.project_root.to_s).wait
180
- exit_code = result.status.exitstatus
181
-
182
- case exit_code
183
- when 0
184
- format_output(result.output, workspace: workspace,
185
- pattern: pattern, path: path)
186
- when 1
187
- no_match_message(pattern: pattern, path: path)
188
- else
189
- stderr = result.output.strip
190
- stderr = "exited #{exit_code}" if stderr.empty?
191
- "Error: ripgrep: #{stderr}"
192
- end
193
- rescue Filesystem::Error => e
194
- "Error: #{e.message}"
195
- end
196
-
197
- # @return [Integer] flags for {File.fnmatch?}: +FNM_PATHNAME+ for
198
- # +**+ recursion + path-aware +/+ matching, +FNM_EXTGLOB+ for
199
- # +{a,b}+ alternation, +FNM_DOTMATCH+ to match dotfiles (rg
200
- # does this when +--hidden+ is set).
201
- FNMATCH_FLAGS = File::FNM_PATHNAME | File::FNM_EXTGLOB | File::FNM_DOTMATCH
202
-
203
- # Build the +rg+ argv. User pattern is NOT passed to rg — see
204
- # the class header for why (rg's +--glob+ overrides
205
- # +.gitignore+).
206
- #
207
- # @return [Array<String>]
208
- def self.build_argv(path:)
209
- [
210
- 'rg',
211
- '--files',
212
- '--color=never',
213
- '--hidden',
214
- '--glob', '!.git/*',
215
- '--', path
216
- ]
217
- end
218
- private_class_method :build_argv
219
-
220
- # Strip the +./+ prefix rg adds when invoked with +.+ as the
221
- # search path, filter to the user pattern with +fnmatch+,
222
- # mtime-sort descending (path ascending as tiebreaker),
223
- # head-truncate at {MAX_BYTES}, append a footer summarizing the
224
- # count.
225
- #
226
- # @return [String]
227
- def self.format_output(raw, workspace:, pattern:, path:)
228
- all_paths = raw.split("\n").reject(&:empty?).map { |p| p.sub(%r{\A\./}, '') }
229
- paths = all_paths.select { |p| File.fnmatch?(pattern, p, FNMATCH_FLAGS) }
230
- return no_match_message(pattern: pattern, path: path) if paths.empty?
231
-
232
- sorted = mtime_sort(paths, workspace.project_root)
233
- joined = sorted.join("\n") + "\n"
234
- content, truncation_marker = head_truncate(joined)
235
- stripped = content.chomp
236
- count = stripped.split("\n").size
237
-
238
- footer = "Found #{pluralize(count, 'file', 'files')}."
239
- [stripped, '', footer + truncation_marker].join("\n")
240
- end
241
- private_class_method :format_output
242
-
243
- # mtime descending; path ascending for stable order on ties.
244
- #
245
- # @return [Array<String>]
246
- def self.mtime_sort(paths, base)
247
- paths
248
- .map { |p| [p, mtime_of(base + p)] }
249
- .sort_by { |(p, m)| [-m, p] }
250
- .map(&:first)
251
- end
252
- private_class_method :mtime_sort
253
-
254
- # @return [Float] epoch-seconds mtime; 0 for paths we can't stat
255
- # (race between rg listing and our stat, deleted symlinks,
256
- # etc.). The fallback puts unstattable entries at the bottom.
257
- def self.mtime_of(absolute)
258
- File.mtime(absolute).to_f
259
- rescue Errno::ENOENT
260
- 0.0
261
- end
262
- private_class_method :mtime_of
263
-
264
- # Head-truncate +raw+ to {MAX_BYTES}, cutting at the last newline
265
- # boundary so the final row is never partial. Returns the
266
- # truncated content and a marker String (empty if no truncation).
267
- #
268
- # @return [Array(String, String)]
269
- def self.head_truncate(raw)
270
- total = raw.bytesize
271
- return [raw, ''] if total <= MAX_BYTES
272
-
273
- head = raw.byteslice(0, MAX_BYTES)
274
- last_nl = head.rindex("\n")
275
- head = head.byteslice(0, last_nl) if last_nl
276
- omitted = total - head.bytesize
277
- marker = "\n\n... [#{omitted} bytes omitted; total was #{total} bytes; " \
278
- 'refine pattern or path] ...'
279
- [head, marker]
280
- end
281
- private_class_method :head_truncate
282
-
283
- # @return [String]
284
- def self.no_match_message(pattern:, path:)
285
- base = "No files match pattern '#{pattern}'"
286
- base += " in #{path}" if path
287
- "#{base}."
288
- end
289
- private_class_method :no_match_message
290
-
291
- # @return [String] +"1 file"+ / +"2 files"+
292
- def self.pluralize(n, sing, plural)
293
- "#{n} #{n == 1 ? sing : plural}"
294
- end
295
- private_class_method :pluralize
296
-
297
- # Verify +rg+ is reachable on +PATH+. Routed through
298
- # {Pikuri::Subprocess.spawn} to honor the subprocess seam. rg
299
- # missing surfaces as +Errno::ENOENT+; an installed rg returns
300
- # exit 0 from +--version+.
301
- #
302
- # @return [void]
303
- # @raise [RuntimeError] if rg is missing
304
- def self.check_binaries!
305
- result = Pikuri::Subprocess.spawn('rg', '--version', chdir: '/').wait
306
- return if result.status.success?
307
-
308
- raise install_hint
309
- rescue Errno::ENOENT
310
- raise install_hint
311
- end
312
- private_class_method :check_binaries!
313
-
314
- # @return [String]
315
- def self.install_hint
316
- "Glob requires 'rg' (ripgrep) on PATH; install via your " \
317
- "distro's package manager (e.g. 'apt install ripgrep')."
318
- end
319
- private_class_method :install_hint
320
- end
321
- end
322
- end