pikuri-workspace 0.1.0 → 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,7 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require 'pathname'
4
- require 'fileutils'
5
4
 
6
5
  module Pikuri
7
6
  module Workspace
@@ -14,50 +13,25 @@ module Pikuri
14
13
  #
15
14
  # +project_root+ is the writable containment ceiling — auto-folded into both
16
15
  # +readable+ and +writable+ (read/write anywhere under it), the base for
17
- # resolving relative LLM paths, and the chdir target for {Bash}/{Grep}/
18
- # {Glob}. There is no separate "cwd": a host wanting the agent in a subtree
19
- # passes that subtree as +project_root+ (+bin/pikuri-code+ also +Dir.chdir+s
20
- # the process there so process and workspace share one anchor). The extra
16
+ # resolving relative LLM paths, and the chdir target for {Search::Grep},
17
+ # {Search::Glob} and a co-wired shell. There is no separate "cwd": a host
18
+ # wanting the agent in a subtree passes that subtree as +project_root+ (and
19
+ # may +Dir.chdir+ the process there so process and workspace share one anchor). The extra
21
20
  # +readable+ list grants read-only roots (toolchains, caches); the extra
22
21
  # +writable+ list grants read+write roots.
23
22
  #
23
+ # +root_writable: false+ makes the project root read-only, so paths still
24
+ # resolve against one base while writes land only in the +writable+ list:
25
+ #
26
+ # Filesystem.new(project_root: '~/Documents', root_writable: false,
27
+ # writable: ['~/Documents/Notes'])
28
+ # # read('Finance/invoice.pdf') ok; write('Notes/x.md') ok; write('x.md') refused
29
+ #
24
30
  # {#resolve_for_read} checks +readable ∪ writable+; {#resolve_for_write}
25
31
  # checks +writable+ only. Neither checks existence — the workspace owns
26
32
  # *containment*, not filesystem state (Read errors on a missing file, Write
27
33
  # +mkdir_p+s its own parents).
28
34
  #
29
- # == Session umbrella ({#internal_temp})
30
- #
31
- # Every workspace owns a per-process umbrella dir, minted lazily (workspaces
32
- # that never touch it pay nothing) as a {Pikuri::Paths.new_temp} — so it
33
- # lands under +~/.cache/pikuri+ (NOT +/tmp+: the sandbox binds {#temp} at
34
- # +/tmp+ inside, and an umbrella already there would bind on top of itself),
35
- # is removed at exit via {Pikuri::Finalizers}, and is stale-swept by
36
- # {Pikuri::Paths.sweep_stale_temps!} at core load. Everything ephemeral lives
37
- # inside it — the {#temp} playground, the Bubblewrap sandbox's per-toolchain
38
- # overlay state — so one +remove_entry+ cleans the lot.
39
- #
40
- # == Optional temp playground / /tmp alias
41
- #
42
- # +temp: true+ adds +<internal_temp>/playground+ to {#writable}, exposed via
43
- # {#temp} as LLM scratch space (default +false+ so specs don't pay the
44
- # mkdir). +alias_tmp_to_temp: true+ (only with +temp:+) rewrites +/tmp/*+
45
- # inputs to {#temp} before containment — the host-side counterpart to the
46
- # sandbox's +--bind <temp> /tmp+, so the LLM uses one path for both.
47
- # +bin/pikuri-code+ flips it on with the bubblewrap sandbox.
48
- #
49
- # == Subprocess environment ({#env})
50
- #
51
- # Workspaces own an {#env} hash that subprocess tools ({Pikuri::Code::Bash})
52
- # thread into {Pikuri::Subprocess.spawn}. Motivating case: the bubblewrap
53
- # sandbox doesn't bind +~/.gitconfig+, so +git commit+ inside fails; the
54
- # workspace resolves the host's effective git identity at {#project_root}
55
- # (so +includeIf+ rules apply) and exposes +GIT_AUTHOR_*+/+GIT_COMMITTER_*+
56
- # that override config with no file in the sandbox. Lazy + memoized (the
57
- # constructor doesn't shell out), falling back to +{}+ if git isn't on PATH
58
- # or no identity is configured. An explicit +env:+ is used verbatim, skipping
59
- # the lookup. Always frozen on the way out.
60
- #
61
35
  # == Containment algorithm
62
36
  #
63
37
  # {#resolve} walks up the input to its deepest existing ancestor,
@@ -75,6 +49,11 @@ module Pikuri
75
49
  # Lexical normalization alone catches 1–3 but misses 4; the walk-up
76
50
  # +realpath+ closes that gap.
77
51
  #
52
+ # The check holds for the path the model named, when it named it: the tool
53
+ # opens the path afterwards, so a symlink swapped in between escapes.
54
+ # Accepted because nothing may change a root while a tool runs (the root
55
+ # +AGENTS.md+ invariant) — +design/decisions.md+ +D_containment_race+.
56
+ #
78
57
  # == Project-root denylist
79
58
  #
80
59
  # A +project_root+ of a system root or home dir makes the whole tree
@@ -97,9 +76,9 @@ module Pikuri
97
76
  /usr /opt /lib /lib64 /bin /sbin /tmp
98
77
  ].map { |p| Pathname.new(p) }.freeze
99
78
 
100
- # @return [Pathname] project root, post-realpath — the writable
101
- # containment ceiling, relative-path base, and Bash/Grep/Glob chdir
102
- # target; always in {#readable}/{#writable}.
79
+ # @return [Pathname] project root, post-realpath — the containment
80
+ # ceiling, relative-path base, and shell/Grep/Glob chdir target;
81
+ # always in {#readable}, in {#writable} unless +root_writable: false+.
103
82
  attr_reader :project_root
104
83
 
105
84
  # @return [Array<Pathname>] read-only roots (writable roots are also
@@ -107,7 +86,7 @@ module Pikuri
107
86
  attr_reader :readable
108
87
 
109
88
  # @return [Array<Pathname>] writable roots (read+write); includes
110
- # {#project_root} and, with +temp: true+, {#temp}. Post-realpath, deduped.
89
+ # {#project_root} unless +root_writable: false+. Post-realpath, deduped.
111
90
  attr_reader :writable
112
91
 
113
92
  # Whether these roots may hold data worth exfiltrating — the lethal
@@ -128,10 +107,11 @@ module Pikuri
128
107
  # Default +false+, because broad disk access means cloned dependencies,
129
108
  # fetched PR branches, saved downloads and package caches: attacker-authored
130
109
  # bytes are the norm, and a hostile README reaches the model verbatim.
131
- # Claim it only when the trusted area is the tool's *entire* reachable set
132
- # — a vouched-for island inside a broad root buys nothing, since the tool
133
- # can still reach everything else. That is why {AllowAll} refuses the flag
134
- # outright rather than merely discouraging it.
110
+ # The claim covers the tool's *entire* reachable set — a vouched-for island
111
+ # inside a broad root buys nothing, since the tool can still reach
112
+ # everything else — so +trusted: true+ refuses any root outside
113
+ # +project_root+: a +~/.m2+ cache or a home skill dir is somebody else's
114
+ # bytes.
135
115
  #
136
116
  # Distinct from the trust-this-directory question a host may ask at boot:
137
117
  # that one asks whether a hostile +.gitattributes+ can *execute code*, this
@@ -142,23 +122,13 @@ module Pikuri
142
122
  # @return [Boolean] default +false+
143
123
  def trusted? = @trusted
144
124
 
145
- # @return [Pathname, nil] the LLM-visible scratch playground (writable, at
146
- # +<internal_temp>/playground+) when +temp: true+, else +nil+; wiped with
147
- # the umbrella at exit.
148
- attr_reader :temp
149
-
150
125
  # @param project_root [String, Pathname] project root; +realpath+'d once,
151
126
  # must exist, must not match {DENIED_PROJECT_ROOTS} or be a +/home+ child.
152
127
  # @param readable [Array<String, Pathname>] extra read-only roots;
153
128
  # +realpath+'d (missing entries raise).
154
129
  # @param writable [Array<String, Pathname>] extra read+write roots; same.
155
- # @param temp [Boolean] +true+ adds +<internal_temp>/playground+ to
156
- # {#writable} and exposes it via {#temp} (minting the umbrella up-front).
157
- # @param alias_tmp_to_temp [Boolean] +true+ (with +temp:+) rewrites +/tmp/*+
158
- # inputs to {#temp}; pairs with the sandbox's +--bind <temp> /tmp+.
159
- # @param env [Hash{String=>String}, nil] subprocess env via {#env}; +nil+
160
- # lazy-derives host git identity from {#project_root}, an explicit hash
161
- # is used verbatim (see §"Subprocess environment").
130
+ # @param root_writable [Boolean] +false+ keeps +project_root+ read-only;
131
+ # writes then land only under +writable+.
162
132
  # @param private [Boolean] these roots may hold sensitive data; see
163
133
  # {#private?}.
164
134
  # @param trusted [Boolean] every byte under these roots is user-authored;
@@ -166,47 +136,19 @@ module Pikuri
166
136
  # @raise [Errno::ENOENT] if any of +project_root+/+readable+/+writable+
167
137
  # doesn't exist.
168
138
  # @raise [Error] if +project_root+ is denied (system root or +/home/*+).
169
- def initialize(project_root:, readable: [], writable: [], temp: false, alias_tmp_to_temp: false, env: nil,
170
- private: false, trusted: false)
139
+ # @raise [ArgumentError] if +trusted: true+ and a +readable+/+writable+
140
+ # root lies outside +project_root+.
141
+ def initialize(project_root:, readable: [], writable: [], root_writable: true, private: false,
142
+ trusted: false)
171
143
  @project_root = Pathname.new(project_root).realpath
172
144
  validate_project_root!(@project_root)
173
145
 
174
146
  @private = private
175
147
  @trusted = trusted
176
148
 
177
- @internal_temp = nil
178
- @temp = temp ? mint_playground : nil
179
- @alias_tmp_to_temp = alias_tmp_to_temp && !@temp.nil?
180
- @env_override = env
181
-
182
- @writable = ([@project_root] + writable.map { |p| Pathname.new(p).realpath } + [@temp].compact).uniq
183
- @readable = (@writable + readable.map { |p| Pathname.new(p).realpath }).uniq
184
- end
185
-
186
- # @return [Boolean] whether {#resolve_for_read}/{#resolve_for_write} rewrite
187
- # +/tmp/*+ inputs to {#temp}.
188
- attr_reader :alias_tmp_to_temp
189
-
190
- # Environment variables for subprocesses spawned in this workspace. Lazy,
191
- # memoized, frozen. With +env: nil+ the first call resolves the host git
192
- # identity for {#project_root} (+GIT_AUTHOR_*+/+GIT_COMMITTER_*+, or +{}+
193
- # if none / no git); an explicit hash is returned frozen without shelling
194
- # out. See §"Subprocess environment".
195
- #
196
- # @return [Hash{String=>String}]
197
- def env
198
- @env ||= (@env_override || compute_git_identity_env).freeze
199
- end
200
-
201
- # Per-workspace ephemeral umbrella, minted lazily as a fresh
202
- # {Pikuri::Paths.new_temp} (reaped at exit, stale-swept at core load) — so
203
- # anything placed inside (the playground, Bubblewrap overlay state) is
204
- # wiped together. Put workspace-owned ephemeral state here, not in a
205
- # sibling.
206
- #
207
- # @return [Pathname]
208
- def internal_temp
209
- @internal_temp ||= Paths.new_temp
149
+ @writable = ((root_writable ? [@project_root] : []) + writable.map { |p| Pathname.new(p).realpath }).uniq
150
+ @readable = ([@project_root] + @writable + readable.map { |p| Pathname.new(p).realpath }).uniq
151
+ validate_trusted_roots! if trusted
210
152
  end
211
153
 
212
154
  # Resolve a user path against the read-set (readable ∪ writable). Returned
@@ -228,16 +170,26 @@ module Pikuri
228
170
  resolve(path, @writable)
229
171
  end
230
172
 
231
- private
173
+ # Whether +path+ sits under a credential denylist entry.
174
+ #
175
+ # {#resolve_for_read} gates a path the *model* supplied; this gates a
176
+ # path a tool **walked** to on its own (a {Listing} row, an +rg+ hit),
177
+ # which no +resolve_+ call ever sees. A scoped Filesystem has no
178
+ # denylist — containment is the readable/writable ceiling — so this is
179
+ # always +false+ here; a whole-host subclass with a credential denylist
180
+ # overrides it, symlink-resolving +path+ first so a +decoy → ~/.ssh+
181
+ # link inside the workspace is caught.
182
+ #
183
+ # @param path [String, Pathname]
184
+ # @return [Boolean]
185
+ def denied?(_path) = false
232
186
 
233
- # Eager-create +<internal_temp>/playground+ (only when +temp: true+):
234
- # touches {#internal_temp} so the umbrella mints now, since the playground
235
- # must be in {#writable} by the end of +initialize+.
236
- def mint_playground
237
- path = internal_temp + 'playground'
238
- FileUtils.mkdir_p(path)
239
- path.realpath
240
- end
187
+ # @return [Array<Pathname>] the denied roots, for callers that can prune
188
+ # a walk up front (+rg --glob '!…'+) instead of filtering its results.
189
+ # Empty here; see {#denied?}.
190
+ def denied_roots = []
191
+
192
+ private
241
193
 
242
194
  def validate_project_root!(canonical)
243
195
  if DENIED_PROJECT_ROOTS.include?(canonical) || canonical.parent.to_s == '/home'
@@ -248,9 +200,18 @@ module Pikuri
248
200
  end
249
201
  end
250
202
 
203
+ def validate_trusted_roots!
204
+ stray = @readable.reject { |r| r.ascend.include?(@project_root) }
205
+ return if stray.empty?
206
+
207
+ raise ArgumentError,
208
+ "trusted: true vouches for every byte the tools can reach, but #{stray.map(&:to_s).join(', ')} " \
209
+ "lies outside project_root '#{@project_root}'; scope the workspace to one root, or drop trusted:"
210
+ end
211
+
251
212
  # See the class header for the algorithm rationale.
252
213
  def resolve(path, roots)
253
- path = apply_tmp_alias(path)
214
+ path = expand_home(path)
254
215
  pn = Pathname.new(path)
255
216
  pn = @project_root + pn unless pn.absolute?
256
217
  cleaned = pn.cleanpath
@@ -259,8 +220,9 @@ module Pikuri
259
220
  existing = existing.parent until existing.exist? || existing.parent == existing
260
221
  base = existing.realpath
261
222
 
262
- matched = roots.find { |r| base == r || base.to_s.start_with?(r.to_s + File::SEPARATOR) }
263
- unless matched
223
+ # Component-wise, not a string-prefix test against +root + "/"+: that
224
+ # one turns a +/+ root into +"//"+ and matches nothing beneath it.
225
+ unless roots.any? { |r| base.ascend.include?(r) }
264
226
  raise Error, "path '#{path}' is outside the workspace " \
265
227
  "(roots: #{roots.map(&:to_s).join(', ')})"
266
228
  end
@@ -268,245 +230,25 @@ module Pikuri
268
230
  base + cleaned.relative_path_from(existing)
269
231
  end
270
232
 
271
- # Resolve the host's effective git identity for {#project_root} via
272
- # +git -C project_root config+ — git's full chain (system → global →
273
- # includeIf → per-repo), so it matches what +git commit+ attributes on
274
- # the host. No git on PATH, a non-zero exit, or an empty field all fall
275
- # back to +{}+; otherwise the full four-entry hash.
276
- def compute_git_identity_env
277
- name = git_config('user.name')
278
- email = git_config('user.email')
279
- return {} if name.nil? || name.empty? || email.nil? || email.empty?
280
-
281
- {
282
- 'GIT_AUTHOR_NAME' => name,
283
- 'GIT_AUTHOR_EMAIL' => email,
284
- 'GIT_COMMITTER_NAME' => name,
285
- 'GIT_COMMITTER_EMAIL' => email
286
- }
287
- end
288
-
289
- def git_config(key)
290
- result = Pikuri::Subprocess.spawn(
291
- 'git', '-C', @project_root.to_s, 'config', key,
292
- chdir: @project_root.to_s
293
- ).wait
294
- result.status.success? ? result.output.strip : nil
295
- rescue Errno::ENOENT
296
- nil
297
- end
298
-
299
- public
300
-
301
- # Whether +path+ sits under a credential denylist entry.
233
+ # Expand a leading +~+ / +~/+ to the home folder, as a shell would:
302
234
  #
303
- # {#resolve_for_read} gates a path the *model* supplied; this gates a
304
- # path a tool **walked** to on its own (a {Listing} row, an +rg+ hit),
305
- # which no +resolve_+ call ever sees. A scoped Filesystem has no
306
- # denylist — containment is the readable/writable ceiling — so this is
307
- # always +false+ here; {AllowAll} overrides it.
235
+ # expand_home('~/.bashrc') # => "/home/alex/.bashrc"
236
+ # expand_home('a/~/b') # => "a/~/b"
308
237
  #
309
- # @param path [String, Pathname]
310
- # @return [Boolean]
311
- def denied?(_path) = false
312
-
313
- # @return [Array<Pathname>] the denied roots, for callers that can prune
314
- # a walk up front (+rg --glob '!…'+) instead of filtering its results.
315
- # Empty here; see {#denied?}.
316
- def denied_roots = []
317
-
318
- private
319
-
320
- # Rewrite +/tmp+ / +/tmp/foo+ inputs to land under {#temp} when
321
- # {#alias_tmp_to_temp} is set; other inputs pass through. In the base
322
- # class so {AllowAll} inherits it.
238
+ # Models write +~/.bashrc+ out of shell habit; left alone it resolves to
239
+ # +<project_root>/~/.bashrc+ and fails as *not found* instead of *outside
240
+ # the workspace*, sending the model off on a detour. +~user+ is left
241
+ # alone (Ruby's expansion of it raises on an unknown user).
323
242
  #
324
- # Coerces first: a caller re-resolving a path it already resolved hands
325
- # back a Pathname, and the whole rest of {#resolve} takes one happily.
326
- def apply_tmp_alias(path)
243
+ # @param path [String, Pathname]
244
+ # @return [String]
245
+ def expand_home(path)
327
246
  path = path.to_s
328
- return path unless @alias_tmp_to_temp
329
- return path if tmp_shadowing_root?(path)
330
- return @temp.to_s if path == '/tmp'
331
- return File.join(@temp.to_s, path[5..]) if path.start_with?('/tmp/')
247
+ return Dir.home if path == '~'
248
+ return File.join(Dir.home, path[2..]) if path.start_with?('~/')
332
249
 
333
250
  path
334
251
  end
335
-
336
- # Whether +path+ lies under a workspace root that itself lives under
337
- # +/tmp+ — a project checked out in +/tmp/scratch+, say.
338
- #
339
- # Those are exactly the paths the rewrite must leave alone. The sandbox
340
- # binds {#temp} at +/tmp+ *before* it binds the workspace roots, so a root
341
- # under +/tmp+ is re-bound over the playground and the subprocess sees the
342
- # real project at its own name; rewriting it host-side would make the file
343
- # tools and +bash+ disagree about what +/tmp/scratch/lib/a.rb+ means, and
344
- # send every absolute in-root path into an empty playground. Lexical on
345
- # purpose — it decides only *whether* to rewrite, and {#resolve} still
346
- # realpaths and re-checks containment afterwards, so no symlink escapes
347
- # through here.
348
- #
349
- # @param path [String]
350
- # @return [Boolean]
351
- def tmp_shadowing_root?(path)
352
- @readable.any? do |root|
353
- root = root.to_s
354
- root.start_with?('/tmp/') && (path == root || path.start_with?("#{root}/"))
355
- end
356
- end
357
-
358
- # Unrestricted variant of {Filesystem}: every path resolves, except paths
359
- # under +denylist:+ (default {DEFAULT_CREDENTIAL_DENYLIST} — +~/.ssh+,
360
- # +~/.aws+, +~/.gnupg+, +~/.docker+, +~/.kube+, +~/.netrc+, +/etc/shadow+)
361
- # still raise. For dev-container / Docker mode where the container is the
362
- # boundary; the denylist is defense-in-depth against prompt-injected
363
- # exfiltration of host credentials bind-mounted in. Pairs with +--yolo+
364
- # (no Confirmer) — but combining with +Code::Bash::Sandbox::Bubblewrap+
365
- # defeats the sandbox (the whole fs ends up bound in), and bash inside the
366
- # sandbox bypasses the denylist anyway, so the intended combo is ALLOW_ALL
367
- # + +Sandbox::NONE+ inside a container.
368
- #
369
- # +project_root:+ is accepted for parity but is not a containment ceiling
370
- # and is NOT validated against {DENIED_PROJECT_ROOTS} (+'/'+ is legitimate
371
- # in a container); it still anchors relative paths and the chdir target.
372
- # +temp:+ behaves as in {Filesystem}.
373
- #
374
- # == Denylist semantics
375
- #
376
- # Each entry is realpath'd lazily at check time when it exists (so a
377
- # symlink +/tmp/decoy → ~/.ssh/id_rsa+ is caught), else falls back to a
378
- # literal-prefix match (blocks the agent *creating* a credential dir the
379
- # user lacks). Pass a reduced or empty +denylist:+ to widen access — but
380
- # only behind an outer egress boundary, since bash bypasses it anyway.
381
- # Prefer the parameter over subclassing.
382
- class AllowAll < Filesystem
383
- # Default credential floor even ALLOW_ALL refuses (read *and* write, and
384
- # {#denied?} for anything a tool walks to) — the default +denylist:+, so
385
- # an unconfigured AllowAll keeps its credential floor out of the box;
386
- # widen only by explicitly passing a smaller list. It is a floor, not a
387
- # boundary: a co-wired {Pikuri::Code::Bash} walks around it entirely. Expanded via
388
- # +ENV['HOME']+ at load, unioned with the +/root+ variants (dev-container
389
- # default user). Frozen.
390
- DEFAULT_CREDENTIAL_DENYLIST = begin
391
- homes = [ENV.fetch('HOME', nil), '/root'].compact.uniq
392
- per_home = %w[.ssh .aws .gnupg .docker .kube .netrc]
393
- user_paths = homes.flat_map { |h| per_home.map { |p| File.join(h, p) } }
394
- (user_paths + %w[/etc/shadow]).map { |p| Pathname.new(p) }.uniq.freeze
395
- end
396
-
397
- # @param project_root [String, Pathname] surface-level root; not
398
- # validated against {DENIED_PROJECT_ROOTS}.
399
- # @param temp [Boolean] as in {Filesystem}.
400
- # @param alias_tmp_to_temp [Boolean] as in {Filesystem} (with +temp:+,
401
- # +/tmp/*+ inputs rewrite to {#temp}).
402
- # @param env [Hash{String=>String}, nil] as in {Filesystem#env}.
403
- # @param denylist [Array<String, Pathname>] paths refused for read or
404
- # write (symlink-resolved descendant match); default
405
- # {DEFAULT_CREDENTIAL_DENYLIST}. Reduce — or +[]+ — ONLY behind an
406
- # outer boundary (kernel-severed/confirmed egress, or a container);
407
- # emptying it without one re-opens credential exfiltration.
408
- # @param private [Boolean] as in {Filesystem#private?}. Accepted, and
409
- # usually right: a whole-host workspace is exactly where someone means
410
- # it.
411
- # @param trusted [Boolean] must be +false+; see {Filesystem#trusted?}.
412
- # @raise [ArgumentError] if +trusted: true+ — the flag cannot be honest
413
- # when the reachable set is the whole host.
414
- def initialize(project_root: Dir.pwd, temp: false, alias_tmp_to_temp: false,
415
- env: nil, denylist: DEFAULT_CREDENTIAL_DENYLIST,
416
- private: false, trusted: false)
417
- # Unrepresentable rather than merely inadvisable: the reachable set is
418
- # the whole host, so no human can vouch for every byte in it.
419
- raise ArgumentError, 'trusted: is not representable on AllowAll — scope the workspace instead' if trusted
420
-
421
- @project_root = Pathname.new(project_root).realpath
422
-
423
- @private = private
424
- @trusted = false
425
-
426
- @internal_temp = nil
427
- @temp = temp ? mint_playground : nil
428
- @alias_tmp_to_temp = alias_tmp_to_temp && !@temp.nil?
429
- @env_override = env
430
- @denylist = denylist.map { |p| Pathname.new(p) }.uniq.freeze
431
-
432
- # Advertise "everything is in scope" via the accessor surface so
433
- # callers inspecting +readable+/+writable+ (prompt rendering, Bubblewrap
434
- # binds) see the intended semantics; actual containment is the denylist.
435
- @writable = [Pathname.new('/').realpath, @temp].compact.uniq
436
- @readable = @writable.dup
437
- end
438
-
439
- # @param path [String, Pathname]
440
- # @return [Pathname]
441
- # @raise [Error] if the resolved path lands under the credential denylist.
442
- def resolve_for_read(path)
443
- resolve_unrestricted(path)
444
- end
445
-
446
- # @param path [String, Pathname]
447
- # @return [Pathname]
448
- # @raise [Error] if the resolved path lands under the credential denylist.
449
- def resolve_for_write(path)
450
- resolve_unrestricted(path)
451
- end
452
-
453
- # The walked-path gate (see {Filesystem#denied?}). Symlink-resolves
454
- # +path+ first, so a +decoy → ~/.ssh+ inside the workspace is caught
455
- # even though nothing ever handed it to a +resolve_+ call.
456
- #
457
- # @param path [String, Pathname]
458
- # @return [Boolean]
459
- def denied?(path)
460
- !denying_root(normalize(path)).nil?
461
- end
462
-
463
- # @return [Array<Pathname>]
464
- def denied_roots = @denylist
465
-
466
- private
467
-
468
- # @param resolved [Pathname] symlink-resolved absolute path
469
- # @return [Pathname, nil] the denylist entry containing +resolved+
470
- def denying_root(resolved)
471
- @denylist.find do |denied|
472
- candidate = denied.exist? ? denied.realpath : denied
473
- resolved == candidate ||
474
- resolved.to_s.start_with?(candidate.to_s + File::SEPARATOR)
475
- end
476
- end
477
-
478
- # @return [Pathname] symlink-resolved; falls back to a lexical cleanup
479
- # for a path that doesn't exist (the agent creating a credential dir
480
- # the user lacks must still be blocked).
481
- def normalize(path)
482
- Pathname.new(path).realpath
483
- rescue SystemCallError
484
- Pathname.new(path).expand_path.cleanpath
485
- end
486
-
487
- def resolve_unrestricted(path)
488
- path = apply_tmp_alias(path)
489
- pn = Pathname.new(path)
490
- pn = @project_root + pn unless pn.absolute?
491
- cleaned = pn.cleanpath
492
-
493
- existing = cleaned
494
- existing = existing.parent until existing.exist? || existing.parent == existing
495
- base = existing.realpath
496
- resolved = base + cleaned.relative_path_from(existing)
497
-
498
- # +resolved+ is already realpath-based, so it goes to the shared
499
- # containment test directly rather than through {#denied?}.
500
- if (denied = denying_root(resolved))
501
- raise Error,
502
- "path '#{path}' resolves under a denied credential location " \
503
- "('#{denied}') — this AllowAll's denylist blocks it. " \
504
- 'Reduce denylist: only behind an outer egress boundary.'
505
- end
506
-
507
- resolved
508
- end
509
- end
510
252
  end
511
253
  end
512
254
  end
@@ -39,7 +39,7 @@ module Pikuri
39
39
  # can't silently vanish from the answer. The price is a caller-visible one:
40
40
  # nothing evaluates +.gitignore+ here, so everything shows except +.git/+ —
41
41
  # +ls+ behaviour, and the one place the file tools diverge on gitignore.
42
- # Full argument in +DECISIONS.md+ +D_directory_listing+.
42
+ # Full argument in +design/decisions.md+ +D_directory_listing+.
43
43
  module Listing
44
44
  # @return [Integer] hard byte cap on rendered output. Same value as
45
45
  # {Search::Glob::MAX_BYTES}; re-declared rather than cross-referenced
@@ -85,14 +85,30 @@ module Pikuri
85
85
  # +""+ when +dir+ has no entries
86
86
  # @raise [SystemCallError] if +dir+ itself can't be opened
87
87
  def self.render(dir, filesystem:, depth: DEFAULT_DEPTH)
88
+ render_with_count(dir, filesystem: filesystem, depth: depth).first
89
+ end
90
+
91
+ # {render} plus how many rows it walked — what a caller needs for a
92
+ # display line, and not recoverable from the rendered text (nested rows
93
+ # and a truncation marker are lines too).
94
+ #
95
+ # listing, entries = Listing.render_with_count(root, filesystem: fs)
96
+ #
97
+ # @param dir [String, Pathname] directory to list
98
+ # @param filesystem [Filesystem] consulted per row via +denied?+
99
+ # @param depth [Integer] levels to descend, clamped to {MAX_DEPTH}
100
+ # @return [Array(String, Integer)] the listing (+""+ when empty) and its
101
+ # row count
102
+ # @raise [SystemCallError] if +dir+ itself can't be opened
103
+ def self.render_with_count(dir, filesystem:, depth: DEFAULT_DEPTH)
88
104
  rows = child_rows(dir.to_s, filesystem: filesystem,
89
105
  depth: depth.clamp(1, MAX_DEPTH), indent: '')
90
- return '' if rows.empty?
106
+ return ['', 0] if rows.empty?
91
107
 
92
108
  content, marker = Search::Utils.head_truncate(
93
109
  rows.join("\n"), max_bytes: MAX_BYTES, hint: 'list a subdirectory instead'
94
110
  )
95
- content + marker
111
+ [content + marker, rows.size]
96
112
  end
97
113
 
98
114
  # Rows for +dir+'s immediate children, recursing while +depth+ allows.
@@ -134,7 +150,7 @@ module Pikuri
134
150
  dirs, files = partition_children(absolute)
135
151
  return '[empty]' if dirs.empty? && files.empty?
136
152
 
137
- "[#{pluralize(dirs.size, 'dir')}, #{pluralize(files.size, 'file')}]"
153
+ "[#{Pikuri::Tool.pluralize(dirs.size, 'dir')}, #{Pikuri::Tool.pluralize(files.size, 'file')}]"
138
154
  end
139
155
  private_class_method :summary
140
156
 
@@ -183,12 +199,6 @@ module Pikuri
183
199
  format('%.1f%s', value, unit)
184
200
  end
185
201
  private_class_method :human_size
186
-
187
- # @return [String] +"1 dir"+ / +"4 dirs"+
188
- def self.pluralize(count, noun)
189
- "#{count} #{noun}#{'s' unless count == 1}"
190
- end
191
- private_class_method :pluralize
192
202
  end
193
203
  end
194
204
  end