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.
@@ -13,7 +13,8 @@ module Pikuri
13
13
  #
14
14
  # Three branches on +path+'s on-disk state:
15
15
  #
16
- # 1. *New file* — write, no prompt.
16
+ # 1. *New file* — confirm +"OK to create <path> (<n> bytes)?"+ via
17
+ # {WriteGate}; under +confirm_all_writes: false+, write with no prompt.
17
18
  # 2. *Existing, identical content* — return an +"Error: ..."+ no-op
18
19
  # *before* the confirmer (don't ask to approve a no-change write).
19
20
  # Comparison is byte-strict, BINARY (trailing-newline diffs still confirm).
@@ -25,20 +26,25 @@ module Pikuri
25
26
  # promptless-confirm path), so it gets the diff payload, decline-reason
26
27
  # steering, and unwritable-target short-circuit in every posture.
27
28
  #
28
- # == Confirm-all-writes (opt-in)
29
+ # == Confirm-all-writes (the default)
30
+ #
31
+ # Write.new(workspace: ws, confirmer: c) # every write asks
32
+ # Write.new(workspace: ws, confirmer: c, confirm_all_writes: false) # only overwrites ask
29
33
  #
30
34
  # +confirm_all_writes+ scopes *which* writes are gated, not *how* (overwrites
31
- # use {WriteGate} regardless). +true+ (the OS-helper posture) also confirms
32
- # the *new-file* branch via {WriteGate} — every writable write confirms, an
33
- # unwritable target short-circuits without prompting. +false+ (default) writes
34
- # new files silently; only overwrites confirm. See book/os-assistant.md.
35
+ # use {WriteGate} regardless). +true+ also gates the new-file branch, so
36
+ # every writable write confirms and an unwritable target short-circuits
37
+ # without prompting. +false+ writes new files silently — the coding-agent
38
+ # posture, where new files are routine and git is the undo. See
39
+ # book/touching-files.md.
35
40
  #
36
- # == Why ask-on-overwrite (Edit doesn't)
41
+ # == Why an overwrite always asks (Edit can opt out)
37
42
  #
38
- # Write confirms an overwrite where {Edit} stays promptless — the two-guard
39
- # asymmetry (the shared read-before-edit gate plus Edit's +old_string+
40
- # content-check, which Write lacks so a hallucinated +content+ could clobber
41
- # the file) is in +pikuri-workspace/DESIGN.md+.
43
+ # Under +confirm_all_writes: false+ Write still confirms an overwrite where
44
+ # {Edit} goes promptless — the two-guard asymmetry (the shared
45
+ # read-before-edit gate plus Edit's +old_string+ content-check, which Write
46
+ # lacks so a hallucinated +content+ could clobber the file) is in
47
+ # +pikuri-workspace/design/architecture.md+.
42
48
  #
43
49
  # == Side effects
44
50
  #
@@ -49,8 +55,7 @@ module Pikuri
49
55
  #
50
56
  # Sharing: +P_one_agent+ — it consults one {Workspace}'s read record. The
51
57
  # {Confirmer} is the sharper limit, though: {Confirmer::Terminal} cannot
52
- # serve two agents at once (see its own +== Sharing+), and a shared
53
- # {ReadOnly} makes read-only a VM-wide posture rather than this agent's.
58
+ # serve two agents at once (see its own +== Sharing+).
54
59
  class Write < Pikuri::Tool
55
60
  # Description shown to the LLM (opencode-shape). Per-parameter constraints
56
61
  # live in the parameter descriptions.
@@ -70,18 +75,12 @@ module Pikuri
70
75
  # @param workspace [Workspace] captured for path resolution, the
71
76
  # read-before-overwrite gate, and read-ledger marking
72
77
  # (+resolve_for_write+).
73
- # @param confirmer [Confirmer] consulted (via {WriteGate}) before an
74
- # overwrite with non-identical content, and — under +confirm_all_writes+
75
- # — before new-file writes too.
76
- # @param read_only [ReadOnly, nil] when set and {ReadOnly#active?}, every
77
- # write is refused *before* any filesystem touch — the hard half of the
78
- # read-only posture. +nil+ (default) disables the gate.
79
- # @param confirm_all_writes [Boolean] scopes which writes are gated
80
- # (overwrites always confirm regardless). +true+ (OS-helper posture)
81
- # also confirms the new-file branch and short-circuits an unwritable
82
- # target without prompting; +false+ (default) writes new files silently.
78
+ # @param confirmer [Confirmer] consulted (via {WriteGate}) before every
79
+ # write, or only before an overwrite under +confirm_all_writes: false+.
80
+ # @param confirm_all_writes [Boolean] +false+ writes new files silently;
81
+ # overwrites confirm either way.
83
82
  # @return [Write]
84
- def initialize(workspace:, confirmer:, read_only: nil, confirm_all_writes: false)
83
+ def initialize(workspace:, confirmer:, confirm_all_writes: true)
85
84
  super(
86
85
  name: 'write',
87
86
  description: DESCRIPTION,
@@ -94,10 +93,11 @@ module Pikuri
94
93
  'Full contents to write to the file, e.g. ' \
95
94
  '"class Foo\nend\n".'
96
95
  },
97
- execute: ->(path:, content:) {
96
+ wants_context: true,
97
+ execute: ->(path:, content:, context:) {
98
98
  Write.write(workspace: workspace, confirmer: confirmer,
99
- read_only: read_only, confirm_all_writes: confirm_all_writes,
100
- path: path, content: content)
99
+ confirm_all_writes: confirm_all_writes,
100
+ path: path, content: content, cancellable: context.cancellable)
101
101
  },
102
102
  # No legs: no file bytes enter the model's context (the observation is
103
103
  # an outcome), and a local write is not an external sink.
@@ -118,47 +118,55 @@ module Pikuri
118
118
  # @param confirmer [Confirmer]
119
119
  # @param path [String] raw path from the LLM
120
120
  # @param content [String] bytes to write
121
- # @param read_only [ReadOnly, nil] read-only gate; see {#initialize}
122
- # (default +nil+ for direct callers/specs).
123
- # @param confirm_all_writes [Boolean] see {#initialize} (default +false+).
124
- # @return [String] tool observation
125
- def self.write(workspace:, confirmer:, path:, content:, read_only: nil, confirm_all_writes: false)
126
- return "Error: cannot write #{path} — #{read_only.message}" if read_only&.active?
127
-
121
+ # @param confirm_all_writes [Boolean] see {#initialize}.
122
+ # @param cancellable [Pikuri::Agent::Control::Cancellable] the calling
123
+ # turn's token, for the confirmation.
124
+ # @return [Tool::Result] +"Created, 88 lines"+ / +"Updated, 88 lines (was
125
+ # 90)"+ on a write; {Pikuri::Tool::Result.error} for a refusal or the
126
+ # confirmer's decline. The line counts rather than a diff: pikuri has no
127
+ # in-process differ (a diff-capable chrome renders the
128
+ # {Confirmer::Change} itself).
129
+ def self.write(workspace:, confirmer:, path:, content:, cancellable:, confirm_all_writes:)
128
130
  resolved = workspace.resolve_for_write(path)
129
131
 
130
132
  if resolved.exist?
131
- return "Error: #{path} is a directory" if resolved.directory?
133
+ return Tool::Result.error("#{path} is a directory") if resolved.directory?
132
134
 
133
135
  unless workspace.read?(resolved)
134
- return "Error: #{path} exists but has not been read this conversation; " \
135
- 'use the read tool first so you do not clobber unread changes.'
136
+ return Tool::Result.error("#{path} exists but has not been read this conversation; " \
137
+ 'use the read tool first so you do not clobber unread changes.')
136
138
  end
137
139
 
138
140
  existing = read_for_compare(resolved, path)
139
141
 
140
142
  if existing == content.b
141
- return "Error: #{path} already contains exactly this content — " \
142
- 'no write needed. If you intended a change, re-read the ' \
143
- 'file and try again.'
143
+ return Tool::Result.error("#{path} already contains exactly this content — " \
144
+ 'no write needed. If you intended a change, re-read the ' \
145
+ 'file and try again.')
144
146
  end
145
147
 
146
148
  gate = WriteGate.check(
147
149
  confirmer: confirmer, path: path, resolved: resolved,
148
150
  question: "OK to overwrite #{path}: #{existing.bytesize} → #{content.bytesize} bytes?",
149
- change: Confirmer::Change.new(path: path, old: existing, new: content.b)
151
+ change: Confirmer::Change.new(path: path, old: existing, new: content.b),
152
+ cancellable: cancellable
150
153
  )
151
154
  return gate if gate
152
155
 
153
156
  write_bytes(resolved, content)
154
157
  workspace.mark_read(resolved)
155
- "Updated #{path} (#{existing.bytesize} → #{content.bytesize} bytes)"
158
+ Tool::Result.new(
159
+ content: "Updated #{path} (#{existing.bytesize} → #{content.bytesize} bytes)",
160
+ summary: "Updated, #{Pikuri::Tool.pluralize(content.lines.size, 'line')} " \
161
+ "(was #{existing.lines.size})"
162
+ )
156
163
  else
157
164
  if confirm_all_writes
158
165
  gate = WriteGate.check(
159
166
  confirmer: confirmer, path: path, resolved: resolved,
160
167
  question: "OK to create #{path} (#{content.bytesize} bytes)?",
161
- change: Confirmer::Change.new(path: path, old: nil, new: content.b)
168
+ change: Confirmer::Change.new(path: path, old: nil, new: content.b),
169
+ cancellable: cancellable
162
170
  )
163
171
  return gate if gate
164
172
  end
@@ -167,12 +175,13 @@ module Pikuri
167
175
  # A just-authored file counts as read: the model supplied its
168
176
  # full bytes, so a follow-up edit needn't re-read it.
169
177
  workspace.mark_read(resolved)
170
- "Created #{path} (#{content.bytesize} bytes)"
178
+ Tool::Result.new(content: "Created #{path} (#{content.bytesize} bytes)",
179
+ summary: "Created, #{Pikuri::Tool.pluralize(content.lines.size, 'line')}")
171
180
  end
172
181
  rescue Filesystem::Error, Error => e
173
- "Error: #{e.message}"
182
+ Tool::Result.error(e.message)
174
183
  rescue Errno::EACCES => e
175
- "Error: cannot write #{path}: #{e.message}"
184
+ Tool::Result.error("cannot write #{path}: #{e.message}")
176
185
  end
177
186
 
178
187
  # Internal-only signal for an LLM-actionable precondition Write detects
@@ -2,9 +2,9 @@
2
2
 
3
3
  module Pikuri
4
4
  module Workspace
5
- # The shared pre-write gate for the *confirm-all-writes* posture (the
6
- # OS-helper wiring; book/os-assistant.md). Before a {Write}/{Edit} mutates a file
7
- # it runs {.check}, which:
5
+ # The shared pre-write gate behind every confirmed write
6
+ # (book/touching-files.md). Before a {Write}/{Edit} mutates a file it runs
7
+ # {.check}, which:
8
8
  #
9
9
  # 1. **Short-circuits an unwritable target.** If the user can't write the
10
10
  # path, the write would fail anyway and confirming a doomed write is
@@ -13,14 +13,19 @@ module Pikuri
13
13
  # in-process as the real user (only *bash* is sandboxed), so
14
14
  # +File.writable?+ is real. Subsumes +/etc+ / +/boot+ — no path list.
15
15
  # 2. **Confirms with a diff.** Else ask the human via a {Confirmer::Change}
16
- # payload (the chrome renders the diff), surfacing the decline reason on
17
- # no.
16
+ # payload (the chrome renders the diff); a decline answers with the
17
+ # decision's own observation.
18
18
  #
19
19
  # Stateless module (composition, not a base class); both tools call {.check}
20
20
  # and return on a non-nil result. {Write} always routes an overwrite through
21
- # it (its confirmer is mandatory; +confirm_all_writes+ only decides whether
22
- # new-file writes go through too); {Edit} stays promptless unless a confirmer
23
- # is passed, then every edit routes through it.
21
+ # it; +confirm_all_writes: false+ lets a new file skip it and makes {Edit}
22
+ # skip it entirely.
23
+ #
24
+ # If a frequent-writing agent ever wants some writes to skip the prompt,
25
+ # grow an allowlist of safe paths (deny-by-default = confirm, like
26
+ # +PASSIVE_BINARIES+), never a denylist of sensitive ones — the denylist
27
+ # loses the enumeration game. Confirming every write is that allowlist,
28
+ # empty.
24
29
  module WriteGate
25
30
  module_function
26
31
 
@@ -29,14 +34,19 @@ module Pikuri
29
34
  # @param resolved [Pathname] resolved write target.
30
35
  # @param question [String] one-line confirm headline.
31
36
  # @param change [Confirmer::Change] the diff payload (old/new bytes).
32
- # @return [String, nil] an +"Error: ..."+ observation to return
33
- # immediately (unwritable, or declined), or +nil+ to proceed.
34
- def check(confirmer:, path:, resolved:, question:, change:)
37
+ # @param cancellable [Pikuri::Agent::Control::Cancellable] the calling
38
+ # turn's token, for {Confirmer#ask}.
39
+ # @return [Pikuri::Tool::Result, nil] the observation to return at once
40
+ # (unwritable, rejected or redirected), or +nil+ to proceed.
41
+ # @raise [Pikuri::Agent::Control::Cancellable::Cancelled] when the turn
42
+ # is cancelled while the question waits.
43
+ def check(confirmer:, path:, resolved:, question:, change:, cancellable:)
35
44
  return permission_denied(path) unless writable_target?(resolved)
36
45
 
37
- case confirmer.ask(request: Confirmer::Request.new(question: question, change: change))
38
- in Confirmer::Rejected(reason:) then declined(path, reason)
39
- else nil
46
+ case decision = confirmer.ask(request: Confirmer::Request.new(question: question, change: change),
47
+ cancellable: cancellable)
48
+ in Confirmer::Approved then nil
49
+ in Confirmer::Rejected | Confirmer::Redirected then decision.observation("the write to #{path}")
40
50
  end
41
51
  end
42
52
 
@@ -54,18 +64,10 @@ module Pikuri
54
64
  end
55
65
 
56
66
  # @param path [String]
57
- # @return [String]
67
+ # @return [Pikuri::Tool::Result]
58
68
  def permission_denied(path)
59
- "Error: permission denied — cannot write #{path} as this user; " \
60
- 'ask the user to make the change themselves (e.g. with sudo).'
61
- end
62
-
63
- # @param path [String]
64
- # @param reason [String, nil] the human's optional decline steering.
65
- # @return [String]
66
- def declined(path, reason)
67
- reason ? "Error: user declined the write to #{path}: #{reason}" \
68
- : "Error: user declined the write to #{path}."
69
+ Pikuri::Tool::Result.error("permission denied — cannot write #{path} as this user; " \
70
+ 'ask the user to make the change themselves (e.g. with sudo).')
69
71
  end
70
72
  end
71
73
  end
@@ -13,7 +13,10 @@ require 'pikuri-core'
13
13
  # Zeitwerk infers +Pikuri+ from pikuri-core and auto-vivifies
14
14
  # +Pikuri::Workspace+ as a module from the +pikuri/workspace/+
15
15
  # directory, so individual files like +lib/pikuri/workspace/read.rb+
16
- # 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
+
17
20
  module Pikuri
18
21
  module Workspace
19
22
  LOADER = Zeitwerk::Loader.new
@@ -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.1.0
4
+ version: 0.2.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Martin Vysny
@@ -15,14 +15,14 @@ dependencies:
15
15
  requirements:
16
16
  - - '='
17
17
  - !ruby/object:Gem::Version
18
- version: 0.1.0
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.1.0
25
+ version: 0.2.0
26
26
  - !ruby/object:Gem::Dependency
27
27
  name: reline
28
28
  requirement: !ruby/object:Gem::Requirement
@@ -41,7 +41,7 @@ description: |
41
41
  pikuri-workspace adds "operate on a directory tree" to pikuri-core
42
42
  agents: the +Pikuri::Workspace::Filesystem+ class that scopes
43
43
  filesystem access to an anchor + explicit readable / writable
44
- prefix lists (with optional ephemeral temp playground), the
44
+ prefix lists, the
45
45
  +Pikuri::Workspace::Confirmer+ seam (+AUTO_APPROVE+ + +TERMINAL+)
46
46
  for user-state mutations, and five tools wired to those seams:
47
47
  +Pikuri::Workspace::Read+, +Pikuri::Workspace::Write+,
@@ -63,22 +63,21 @@ files:
63
63
  - lib/pikuri/workspace/file_list.rb
64
64
  - lib/pikuri/workspace/filesystem.rb
65
65
  - lib/pikuri/workspace/listing.rb
66
- - lib/pikuri/workspace/project_root.rb
67
66
  - lib/pikuri/workspace/read.rb
68
- - lib/pikuri/workspace/read_only.rb
69
67
  - lib/pikuri/workspace/search/glob.rb
70
68
  - lib/pikuri/workspace/search/grep.rb
71
69
  - lib/pikuri/workspace/search/utils.rb
72
70
  - lib/pikuri/workspace/workspace.rb
73
71
  - lib/pikuri/workspace/write.rb
74
72
  - lib/pikuri/workspace/write_gate.rb
75
- homepage: https://codeberg.org/mvysny/pikuri
73
+ - prompts/pikuri-files.txt
74
+ homepage: https://github.com/mvysny/pikuri
76
75
  licenses:
77
76
  - MIT
78
77
  metadata:
79
- source_code_uri: https://codeberg.org/mvysny/pikuri/src/branch/master
80
- changelog_uri: https://codeberg.org/mvysny/pikuri/src/branch/master/CHANGELOG.md
81
- 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
82
81
  rubygems_mfa_required: 'true'
83
82
  rdoc_options: []
84
83
  require_paths:
@@ -1,77 +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 for a VCS
8
- # marker (+.git+ / +.hg+ / +.svn+). Host binaries use it to decide the
9
- # {Filesystem} +project_root:+ — the writable containment ceiling and (under
10
- # the +Bubblewrap+ sandbox) the bind-mount root, so +git+/+make+ can climb
11
- # inside the sandbox to find +<repo>/.git+ / +<repo>/Makefile+.
12
- #
13
- # == Why VCS-only markers
14
- #
15
- # Build-system fallbacks (+Gemfile+, +pyproject.toml+, +package.json+,
16
- # +pom.xml+, +build.gradle+, ...) were rejected: they aren't reliable root
17
- # markers in multi-module setups (a Gradle subproject, a Maven module, a
18
- # yarn-workspaces package each has its own), so climbing for them lands on
19
- # the nearest subtree root — and a wrong project_root means the sandbox
20
- # bind-mounts the wrong tree and +git+ can't see the real +.git+. VCS markers
21
- # sit only at the actual root (or a submodule root, the user's intended
22
- # boundary when they cd'd in).
23
- #
24
- # If no marker is found within the safe-climb bounds, {.find} returns +nil+
25
- # and the caller falls back to the launch +cwd+ (losing visibility to sibling
26
- # code; +git init+ or invoke from the project root to fix).
27
- #
28
- # == Safety bounds
29
- #
30
- # The climb refuses to enter the home directory or a system root
31
- # ({DENIED_CLIMB_ROOTS}) — reaching either means "left the project tree" and
32
- # the climb stops. The starting +cwd+ is always considered even if banned
33
- # (the user invoked there); only ancestors are gated.
34
- #
35
- # == Priority
36
- #
37
- # All +markers+ are checked at each ancestor before climbing, so the
38
- # *nearest* VCS marker wins regardless of type.
39
- module ProjectRoot
40
- # Climb-up boundary. Overlaps {Filesystem::DENIED_PROJECT_ROOTS} but kept
41
- # separate — different semantics (climb boundary vs. project_root
42
- # rejection), may drift apart.
43
- DENIED_CLIMB_ROOTS = %w[
44
- / /etc /var /proc /sys /dev /boot /root
45
- /usr /opt /lib /lib64 /bin /sbin /tmp
46
- ].map { |p| Pathname.new(p) }.freeze
47
-
48
- # VCS metadata dirs/files. +.git+ is the common case; +.hg+/+.svn+ for the
49
- # rare users on those. +File.exist?+ matches both a directory (normal
50
- # checkout) and a regular file (+.git+ in a worktree/submodule).
51
- VCS_MARKERS = %w[.git .hg .svn].freeze
52
-
53
- # Find the nearest ancestor of +cwd+ containing any of +markers+. See the
54
- # class header for the safety bounds and priority.
55
- #
56
- # @param cwd [String, Pathname] starting dir; +realpath+'d so symlinked
57
- # checkouts don't bounce out of the tree.
58
- # @param markers [Array<String>] VCS marker names; default {VCS_MARKERS}.
59
- # @return [Pathname, nil] the matching ancestor, or +nil+ if none found
60
- # within the safe-climb bounds (caller falls back to +cwd+).
61
- def self.find(cwd:, markers: VCS_MARKERS)
62
- current = Pathname.new(cwd).realpath
63
- home = Pathname.new(Dir.home).realpath
64
- loop do
65
- return current if markers.any? { |m| current.join(m).exist? }
66
-
67
- parent = current.parent
68
- return nil if parent == current # at the filesystem root
69
- return nil if parent == home # crossing into $HOME
70
- return nil if DENIED_CLIMB_ROOTS.include?(parent)
71
-
72
- current = parent
73
- end
74
- end
75
- end
76
- end
77
- end
@@ -1,134 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- module Pikuri
4
- module Workspace
5
- # A workspace-scoped read-only flag: when active, the mutating file tools
6
- # ({Write}/{Edit}) refuse to write and return a read-only observation
7
- # instead. A plain shared boolean with change notification — the host
8
- # constructs one and hands it to {Workspace::Extension} (which threads it
9
- # into Write/Edit) and to whatever drives it.
10
- #
11
- # Enforcement is the point, so a prompt-only "plan mode" is not a cheaper
12
- # version of this: an outside-model review (Grok 4.6, 2026-08) rated the
13
- # posture it *couldn't* talk its way past over being told to "think step by
14
- # step and then start editing".
15
- #
16
- # == What this does NOT gate: Bash
17
- #
18
- # This governs only {Write}/{Edit}, **not** {Pikuri::Code::Bash}. A shell
19
- # command is Turing-complete with no reliable static "does this write" test
20
- # (+echo+ + redirect, +sed -i+, +>+, +dd+, a Makefile target), so we make no
21
- # attempt to gate Bash and don't pretend to: a "read-only" workspace can
22
- # still mutate disk through bash, subject only to bash's own confirmer. A
23
- # truly inert posture must also withhold or sandbox bash; this flag is not
24
- # that boundary.
25
- #
26
- # == Two writers, one flag
27
- #
28
- # The single source of truth for "are writes disabled now". Both a host (a
29
- # key binding, a slash command) and a feature on top (pikuri-code's
30
- # +enter_plan_mode+/+exit_plan_mode+ via {#activate!}/{#deactivate!}) flip
31
- # the *same* instance. {#on_change} lets an observer (pikuri-code re-emits it
32
- # as {Pikuri::Code::PlanModeChanged}) render the posture continuously.
33
- #
34
- # == Not an Agent control
35
- #
36
- # Deliberately not under +Pikuri::Agent::Control+: unlike {StepLimit} /
37
- # +Cancellable+ / +Interloper+, the loop never reads this — only Write/Edit's
38
- # +execute+ does (the loop can't deny a tool call *and* feed the model an
39
- # explanatory observation, so the refusal lives in the tool). It's a
40
- # workspace property, not a loop control.
41
- #
42
- # Thread-safe: the two writers may be on different threads, so the
43
- # compare-and-set in {#flip} is +Mutex+-guarded (a read-then-write isn't
44
- # atomic under the GVL; getting it wrong would fire {#on_change} twice or
45
- # zero times). Callbacks run *outside* the lock so a re-entrant or blocking
46
- # one can't deadlock the next flip.
47
- class ReadOnly
48
- # Default reason clause when the host gives no +message:+. Posture-agnostic
49
- # — it must NOT assume plan mode (a host can engage read-only for other
50
- # reasons); {Write}/{Edit} splice it after their own "cannot <verb> <path>
51
- # — " prefix. A driving feature (plan mode) passes its own — see
52
- # {Pikuri::Code::Extension::PLAN_MODE_READONLY_MESSAGE}.
53
- #
54
- # @return [String]
55
- DEFAULT_MESSAGE = 'the workspace is read-only, so changes are disabled right now'
56
-
57
- # @param active [Boolean] initial posture; +true+ starts read-only (a
58
- # +--plan+ startup flag).
59
- # @param message [String] the reason clause {Write}/{Edit} append; default
60
- # {DEFAULT_MESSAGE}. Immutable — the host supplies the wording.
61
- def initialize(active: false, message: DEFAULT_MESSAGE)
62
- @mutex = Mutex.new
63
- @active = active
64
- @message = message
65
- @on_change = []
66
- end
67
-
68
- # @return [String] the reason clause to surface when a write is
69
- # refused; see {#initialize}.
70
- attr_reader :message
71
-
72
- # @return [Boolean] whether writes are currently disabled.
73
- # Observable from any thread.
74
- def active?
75
- @mutex.synchronize { @active }
76
- end
77
-
78
- # Turn the posture on. Idempotent (no {#on_change} when already active);
79
- # safe off the loop thread.
80
- #
81
- # @return [void]
82
- def activate!
83
- flip(true)
84
- end
85
-
86
- # Turn the posture off. Idempotent (no {#on_change} when already inactive);
87
- # safe off the loop thread.
88
- #
89
- # @return [void]
90
- def deactivate!
91
- flip(false)
92
- end
93
-
94
- # Register a callback fired once per real transition, with the new state.
95
- # Guarded so a late registration races safely with a concurrent flip.
96
- #
97
- # @yieldparam active [Boolean] the new posture
98
- # @return [void]
99
- # @raise [ArgumentError] when called without a block
100
- def on_change(&blk)
101
- raise ArgumentError, 'on_change requires a block' unless block_given?
102
-
103
- @mutex.synchronize { @on_change << blk }
104
- nil
105
- end
106
-
107
- # @return [String] short label for debug prints; reflects the
108
- # current posture.
109
- def to_s
110
- "ReadOnly(#{active? ? 'on' : 'off'})"
111
- end
112
-
113
- private
114
-
115
- # Compare-and-set under the lock; fan out to {#on_change} outside it, only
116
- # when the value actually changed.
117
- #
118
- # @param target [Boolean] desired posture
119
- # @return [void]
120
- def flip(target)
121
- callbacks = @mutex.synchronize do
122
- next nil if @active == target
123
-
124
- @active = target
125
- @on_change.dup
126
- end
127
- return nil unless callbacks
128
-
129
- callbacks.each { |cb| cb.call(target) }
130
- nil
131
- end
132
- end
133
- end
134
- end