rubik 0.15.3 → 0.15.4

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.
Files changed (58) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +45 -3
  3. data/lib/rubik/adapter/node.rb +3 -2
  4. data/lib/rubik/ast/extractor.rb +1 -1
  5. data/lib/rubik/ast/graph_extensions.rb +3 -1
  6. data/lib/rubik/ast/treesitter_extractor.rb +1 -1
  7. data/lib/rubik/buffer/manager.rb +5 -3
  8. data/lib/rubik/buffer/snapshot.rb +3 -2
  9. data/lib/rubik/concurrency/errors.rb +3 -1
  10. data/lib/rubik/config/coercion.rb +26 -0
  11. data/lib/rubik/config/env_loader.rb +1 -2
  12. data/lib/rubik/config/scoped.rb +5 -20
  13. data/lib/rubik/config/secret_policy.rb +3 -2
  14. data/lib/rubik/config/store.rb +5 -2
  15. data/lib/rubik/config.rb +7 -13
  16. data/lib/rubik/connect/models_dev.rb +13 -11
  17. data/lib/rubik/errors.rb +5 -4
  18. data/lib/rubik/event_bus.rb +0 -1
  19. data/lib/rubik/llm/client.rb +2 -1
  20. data/lib/rubik/llm/registry.rb +1 -1
  21. data/lib/rubik/lsp/client.rb +0 -9
  22. data/lib/rubik/lsp/transport.rb +2 -1
  23. data/lib/rubik/mcp/boot_run.rb +15 -14
  24. data/lib/rubik/mcp/errors.rb +3 -1
  25. data/lib/rubik/mcp/manager.rb +6 -6
  26. data/lib/rubik/orchestrator/auto_apply.rb +2 -1
  27. data/lib/rubik/orchestrator/goal_ledger/suspend_lifecycle.rb +4 -1
  28. data/lib/rubik/orchestrator/subagent/profile_snapshot.rb +4 -2
  29. data/lib/rubik/orchestrator/subagent/supervisor.rb +23 -8
  30. data/lib/rubik/orchestrator/tool_circuit_breaker.rb +3 -1
  31. data/lib/rubik/orchestrator/tool_timeout.rb +3 -2
  32. data/lib/rubik/platform/process.rb +104 -82
  33. data/lib/rubik/plugin/manager.rb +0 -1
  34. data/lib/rubik/plugin/package_inventory.rb +3 -1
  35. data/lib/rubik/repl/hooks.rb +0 -1
  36. data/lib/rubik/repl/interrupt_handler.rb +5 -1
  37. data/lib/rubik/repl/lifecycle.rb +1 -1
  38. data/lib/rubik/repl/terminal_guard.rb +0 -8
  39. data/lib/rubik/runtime/context.rb +3 -2
  40. data/lib/rubik/runtime/overlay_storage.rb +3 -3
  41. data/lib/rubik/runtime/repair_probe.rb +50 -21
  42. data/lib/rubik/runtime/task_manager.rb +81 -82
  43. data/lib/rubik/sandbox/runner.rb +1 -1
  44. data/lib/rubik/security/audit_log.rb +1 -1
  45. data/lib/rubik/security/classifier/matcher/options.rb +7 -1
  46. data/lib/rubik/security/classifier/matcher.rb +8 -3
  47. data/lib/rubik/security/classifier/models.rb +8 -0
  48. data/lib/rubik/security/command_gate.rb +105 -77
  49. data/lib/rubik/security/errors.rb +3 -1
  50. data/lib/rubik/security/secret_store.rb +12 -10
  51. data/lib/rubik/session/recorder.rb +11 -6
  52. data/lib/rubik/skills/frontmatter.rb +3 -1
  53. data/lib/rubik/storage/transcript_indexer.rb +9 -3
  54. data/lib/rubik/ui/capability.rb +4 -8
  55. data/lib/rubik/ui/io_probe.rb +24 -0
  56. data/lib/rubik/ui/spinner.rb +3 -2
  57. data/lib/rubik/version.rb +1 -1
  58. metadata +3 -1
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "../errors"
3
4
  require_relative "../log"
4
5
  require_relative "subagent/notices"
5
6
  require_relative "../storage/layout"
@@ -76,7 +77,7 @@ module Rubik
76
77
  # Raised when the disk apply succeeded but the context/AST index sync
77
78
  # failed — the message says the changes ARE on disk so nobody
78
79
  # "recovers" by re-applying a clean buffer.
79
- class SyncFailedError < StandardError; end
80
+ class SyncFailedError < Rubik::Error; end
80
81
 
81
82
  # Canonical effect: apply the dirty buffer, then sync context/AST
82
83
  # unless nothing was applied. Errors PROPAGATE (the main path
@@ -91,11 +91,14 @@ module Rubik
91
91
 
92
92
  # Satır links'indeki askı damgası meta'sını çözer (bozuk JSON →
93
93
  # nil: load dürüst devam eder, yalnız sayaç geri yüklenemez).
94
+ # Ayrıştırma arızası debug'da görünür: tekrarlayan bozulma deseni
95
+ # sessizce yok olmaz.
94
96
  def parse_suspend_meta(row)
95
97
  raw = row.dig("links", "suspended")
96
98
  parsed = JSON.parse(raw.to_s)
97
99
  parsed.is_a?(Hash) ? parsed : nil
98
- rescue StandardError
100
+ rescue StandardError => e
101
+ Rubik::Log.debug(:goal_ledger, "goal ledger suspend metadata parse failed: #{e.class}: #{e.message.to_s.chars.first(120).join}")
99
102
  nil
100
103
  end
101
104
  end
@@ -1,9 +1,11 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "../../errors"
4
+
3
5
  module Rubik
4
6
  module Orchestrator
5
7
  module Subagent
6
- class UnsatisfiedCoeffectsError < StandardError
8
+ class UnsatisfiedCoeffectsError < Rubik::Error
7
9
  attr_reader :profile_name, :missing
8
10
 
9
11
  def initialize(profile_name, missing)
@@ -13,7 +15,7 @@ module Rubik
13
15
  end
14
16
  end
15
17
 
16
- class ReservedProfileError < StandardError; end
18
+ class ReservedProfileError < Rubik::Error; end
17
19
 
18
20
  # Per-spawn copy of the profile fields that affect activation and tool
19
21
  # visibility. Registry updates replace future snapshots; they never
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "monitor"
4
+ require_relative "../../errors"
4
5
  require_relative "../../platform"
5
6
  require_relative "../task_cancellation"
6
7
  require_relative "type_registry"
@@ -24,11 +25,14 @@ require_relative "conversation_id"
24
25
  module Rubik
25
26
  module Orchestrator
26
27
  module Subagent
27
- class DepthExceededError < StandardError; end
28
- class ConcurrencyExceededError < StandardError; end
28
+ class DepthExceededError < Rubik::Error; end
29
+ class ConcurrencyExceededError < Rubik::Error; end
29
30
  # New owned work after task cancellation (issue #125): the owner's token
30
31
  # is already cancelled — spawning into it would violate "no pending owned
31
32
  # descendant starts after cancellation".
33
+ # Deliberately NOT under Rubik::Error (issue #652): this is the
34
+ # cancellation-refusal control-flow signal, so a future generic
35
+ # `rescue Rubik::Error` catcher must not intercept the spawn refusal.
32
36
  class TaskCancelledError < StandardError; end
33
37
 
34
38
  # Root Supervisor Agent governing the entire subagent process hierarchy:
@@ -89,14 +93,25 @@ module Rubik
89
93
  @result_archive = ResultArchive.new(config: @config)
90
94
 
91
95
  if @event_bus.respond_to?(:subscribe)
92
- @event_bus.subscribe(Notices::ERROR_PAUSED_EVENT) { notify_wait! }
93
- @event_bus.subscribe(Notices::BUDGET_EXHAUSTED_EVENT) { notify_wait! }
94
- @event_bus.subscribe(Notices::COMPLETED_EVENT) { notify_wait! }
95
- @event_bus.subscribe(Notices::QUESTION_EVENT) { notify_wait! } if defined?(Notices::QUESTION_EVENT)
96
+ @wake_subscriptions = [
97
+ [Notices::ERROR_PAUSED_EVENT, @event_bus.subscribe(Notices::ERROR_PAUSED_EVENT) { notify_wait! }],
98
+ [Notices::BUDGET_EXHAUSTED_EVENT, @event_bus.subscribe(Notices::BUDGET_EXHAUSTED_EVENT) { notify_wait! }],
99
+ [Notices::COMPLETED_EVENT, @event_bus.subscribe(Notices::COMPLETED_EVENT) { notify_wait! }]
100
+ ]
101
+ if defined?(Notices::QUESTION_EVENT)
102
+ @wake_subscriptions << [Notices::QUESTION_EVENT,
103
+ @event_bus.subscribe(Notices::QUESTION_EVENT) { notify_wait! }]
104
+ end
96
105
  end
97
106
 
98
- # Register inverse in root context (maestro hook)
99
- @root_context.register_disposable { shutdown_all } if @root_context.respond_to?(:register_disposable)
107
+ # Register inverse in root context (maestro hook): drop the wake
108
+ # subscriptions and then unwind the subagent instances (LIFO).
109
+ return unless @root_context.respond_to?(:register_disposable)
110
+
111
+ @root_context.register_disposable do
112
+ @event_bus.unsubscribe(*@wake_subscriptions.shift) while @wake_subscriptions&.any?
113
+ shutdown_all
114
+ end
100
115
  end
101
116
 
102
117
  def get(id) = @monitor.synchronize { @instances[id.to_s] || @finished[id.to_s] || queued_spec(id.to_s) }
@@ -2,6 +2,8 @@
2
2
 
3
3
  require "monitor"
4
4
 
5
+ require_relative "../errors"
6
+
5
7
  # Opt-in failure isolation for tool execution (G19): after `threshold`
6
8
  # consecutive failures of the same tool, short-circuit further calls for a
7
9
  # cooldown instead of burning agent steps on a wedged backend. Disabled by
@@ -13,7 +15,7 @@ module Rubik
13
15
  # Raised by the StepExecutor when a call is refused; the executor's
14
16
  # normal rescue converts it into a failed tool result so the loop
15
17
  # plumbing (events, history) is reused untouched.
16
- class CircuitOpenError < StandardError; end
18
+ class CircuitOpenError < Rubik::Error; end
17
19
 
18
20
  STATES = [:closed, :open, :half_open].freeze
19
21
 
@@ -3,6 +3,7 @@
3
3
  require "monitor"
4
4
 
5
5
  require_relative "../coeffects"
6
+ require_relative "../errors"
6
7
  require_relative "../tools/result"
7
8
 
8
9
  module Rubik
@@ -22,7 +23,7 @@ module Rubik
22
23
  # Raised in the CALLER thread when the join budget expires. The
23
24
  # dispatch seam's rescue converts it into an honest error Result so
24
25
  # the turn continues.
25
- class BudgetExceeded < StandardError
26
+ class BudgetExceeded < Rubik::Error
26
27
  attr_reader :tool_name, :budget_seconds, :elapsed_seconds
27
28
 
28
29
  def initialize(tool_name:, budget_seconds:, elapsed_seconds:)
@@ -117,7 +118,7 @@ module Rubik
117
118
  raise BudgetExceeded.new(tool_name: name, budget_seconds: budget, elapsed_seconds: elapsed)
118
119
  end
119
120
  raise error if error
120
- raise StandardError, "tool worker for '#{name}' died without completing or raising" unless done
121
+ raise Rubik::Error, "tool worker for '#{name}' died without completing or raising" unless done
121
122
 
122
123
  result
123
124
  end
@@ -49,8 +49,7 @@ module Rubik
49
49
  exit_code = 127
50
50
  pid = nil
51
51
  child_identity = nil
52
- watchdog = nil
53
- deadline_hit = false
52
+ deadline_hit = [false]
54
53
  timed_out = false
55
54
 
56
55
  begin
@@ -62,86 +61,12 @@ module Rubik
62
61
  # which re-snapshotted the CURRENT occupant and signaled an
63
62
  # unrelated process after a PID reuse.
64
63
  child_identity = process_identity(pid)
65
- # Deadline watchdog (issue #479): kill the tree from a separate
66
- # thread the moment the deadline fires, so a hung child never
67
- # outlives `timeout`. The kill must NOT ride Timeout.timeout's
68
- # timer thread: its unwind races the kill, and if the unwind wins,
69
- # popen3's ensure joins the still-running child and the timeout
70
- # merely relabels the result instead of bounding the wall clock.
71
- # Instead the watchdog kills first and sets deadline_hit, and the
72
- # Timeout::Error is raised only after the block has returned.
73
- # Cancelled in the inner ensure to keep the watchdog from firing
74
- # into a recycled pid after normal exit.
75
- watchdog = Thread.new(pid, timeout.to_f, child_identity) do |w_pid, w_deadline, w_identity|
76
- slept = false
77
- begin
78
- sleep w_deadline
79
- slept = true
80
- # Race guard (issue #597): only flag a timeout when the kill
81
- # actually targets a still-live process — a child that completes
82
- # exactly as the deadline fires keeps its real exit status
83
- # instead of being relabeled exit 124.
84
- # A recycled PID is "alive" but is not our child: do not
85
- # relabel its success as a timeout and do not signal it.
86
- deadline_hit = true if identity_unchanged?(w_pid, w_identity) && process_alive?(w_pid)
87
- kill_tree(w_pid, identity: w_identity)
88
- rescue StandardError => e
89
- # Issue #597-2 follow-up: a kill-path failure at the deadline
90
- # must never silently drop the timeout — the deadline has
91
- # fired, so mark it (the caller below raises Timeout::Error
92
- # and still attempts its own kill) and log the failure.
93
- # `slept` guards against a spurious mark if the thread itself
94
- # dies before the deadline. Thread#kill lands as an
95
- # uncatchable KillError, so a normal-exit cancellation never
96
- # reaches this rescue.
97
- if slept
98
- deadline_hit = true
99
- Rubik::Log.warn(:platform, "popen_capture deadline kill failed for pid #{w_pid}: " \
100
- "#{e.class}: #{e.message}")
101
- end
102
- end
103
- end
104
- begin
105
- stdin.close
106
- rescue StandardError => e
107
- on_io_error.call(:stdin_close, e)
108
- end
109
- t_out = Thread.new do
110
- stdout.read
111
- rescue StandardError => e
112
- on_io_error.call(:stdout_read, e)
113
- ""
114
- end
115
- t_err = Thread.new do
116
- stderr.read
117
- rescue StandardError => e
118
- on_io_error.call(:stderr_read, e)
119
- ""
120
- end
121
- begin
122
- stdout_str = t_out.value.to_s
123
- stderr_str = t_err.value.to_s
124
- status = wait_thr.value
125
- exit_code = status.exitstatus || (status.signaled? ? (128 + (status.termsig || 1)) : 1)
126
- ensure
127
- begin
128
- watchdog&.kill
129
- rescue StandardError
130
- nil
131
- end
132
- begin
133
- t_out.kill
134
- rescue StandardError => e
135
- on_io_error.call(:stdout_kill, e)
136
- end
137
- begin
138
- t_err.kill
139
- rescue StandardError => e
140
- on_io_error.call(:stderr_kill, e)
141
- end
142
- end
64
+ watchdog = spawn_deadline_watchdog(pid, timeout, child_identity, deadline_hit)
65
+ t_out, t_err = start_drain_threads(stdin, stdout, stderr, on_io_error)
66
+ stdout_str, stderr_str, exit_code =
67
+ collect_drained_output(t_out, t_err, wait_thr, watchdog, on_io_error)
143
68
  end
144
- raise Timeout::Error, "execution expired" if deadline_hit
69
+ raise Timeout::Error, "execution expired" if deadline_hit[0]
145
70
  rescue Timeout::Error
146
71
  timed_out = true
147
72
  kill_tree(pid, identity: child_identity) if pid
@@ -168,7 +93,7 @@ module Rubik
168
93
  # Explicit timeout flag (issue #597): exit code 124 is also a
169
94
  # legitimate exit code of timeout(1) and other workloads, so the
170
95
  # tool layer must not re-derive `timed_out` from the exit code.
171
- timed_out: timed_out || deadline_hit
96
+ timed_out: timed_out || deadline_hit[0]
172
97
  }
173
98
  end
174
99
 
@@ -273,6 +198,103 @@ module Rubik
273
198
 
274
199
  private
275
200
 
201
+ # Deadline watchdog (issue #479): kill the tree from a separate thread
202
+ # the moment the deadline fires, so a hung child never outlives
203
+ # `timeout`. The kill must NOT ride Timeout.timeout's timer thread: its
204
+ # unwind races the kill, and if the unwind wins, popen3's ensure joins
205
+ # the still-running child and the timeout merely relabels the result
206
+ # instead of bounding the wall clock. Instead the watchdog kills first
207
+ # and flags `deadline_hit` (a one-element cell so the flag is visible to
208
+ # the caller), and the Timeout::Error is raised only after the popen3
209
+ # block has returned. Cancelled in the inner ensure (see
210
+ # collect_drained_output) to keep the watchdog from firing into a
211
+ # recycled pid after normal exit.
212
+ def spawn_deadline_watchdog(pid, timeout, child_identity, deadline_hit)
213
+ Thread.new(pid, timeout.to_f, child_identity) do |w_pid, w_deadline, w_identity|
214
+ slept = false
215
+ begin
216
+ sleep w_deadline
217
+ slept = true
218
+ # Race guard (issue #597): only flag a timeout when the kill
219
+ # actually targets a still-live process — a child that completes
220
+ # exactly as the deadline fires keeps its real exit status
221
+ # instead of being relabeled exit 124.
222
+ # A recycled PID is "alive" but is not our child: do not
223
+ # relabel its success as a timeout and do not signal it.
224
+ deadline_hit[0] = true if identity_unchanged?(w_pid, w_identity) && process_alive?(w_pid)
225
+ kill_tree(w_pid, identity: w_identity)
226
+ rescue StandardError => e
227
+ # Issue #597-2 follow-up: a kill-path failure at the deadline
228
+ # must never silently drop the timeout — the deadline has
229
+ # fired, so mark it (the caller below raises Timeout::Error
230
+ # and still attempts its own kill) and log the failure.
231
+ # `slept` guards against a spurious mark if the thread itself
232
+ # dies before the deadline. Thread#kill lands as an
233
+ # uncatchable KillError, so a normal-exit cancellation never
234
+ # reaches this rescue.
235
+ if slept
236
+ deadline_hit[0] = true
237
+ Rubik::Log.warn(:platform, "popen_capture deadline kill failed for pid #{w_pid}: " \
238
+ "#{e.class}: #{e.message}")
239
+ end
240
+ end
241
+ end
242
+ end
243
+
244
+ # Close the child's stdin (the child sees EOF), then spawn one reader
245
+ # thread per output pipe so the OS pipe buffer never fills and
246
+ # deadlocks the child. IO errors during the drain are swallowed via
247
+ # on_io_error so a dying reader cannot crash the capture.
248
+ def start_drain_threads(stdin, stdout, stderr, on_io_error)
249
+ begin
250
+ stdin.close
251
+ rescue StandardError => e
252
+ on_io_error.call(:stdin_close, e)
253
+ end
254
+ t_out = Thread.new do
255
+ stdout.read
256
+ rescue StandardError => e
257
+ on_io_error.call(:stdout_read, e)
258
+ ""
259
+ end
260
+ t_err = Thread.new do
261
+ stderr.read
262
+ rescue StandardError => e
263
+ on_io_error.call(:stderr_read, e)
264
+ ""
265
+ end
266
+ [t_out, t_err]
267
+ end
268
+
269
+ # Wait for the drain threads and the child, map the exit status to a
270
+ # code, then tear the threads down in the ensure: the watchdog first
271
+ # (so it cannot fire into a recycled pid), then the readers.
272
+ def collect_drained_output(t_out, t_err, wait_thr, watchdog, on_io_error)
273
+ begin
274
+ out = t_out.value.to_s
275
+ err = t_err.value.to_s
276
+ status = wait_thr.value
277
+ code = status.exitstatus || (status.signaled? ? (128 + (status.termsig || 1)) : 1)
278
+ ensure
279
+ cancel_watchdog(watchdog)
280
+ stop_drain_thread(t_out, :stdout_kill, on_io_error)
281
+ stop_drain_thread(t_err, :stderr_kill, on_io_error)
282
+ end
283
+ [out, err, code]
284
+ end
285
+
286
+ def cancel_watchdog(watchdog)
287
+ watchdog&.kill
288
+ rescue StandardError
289
+ nil
290
+ end
291
+
292
+ def stop_drain_thread(thread, event, on_io_error)
293
+ thread.kill
294
+ rescue StandardError => e
295
+ on_io_error.call(event, e)
296
+ end
297
+
276
298
  def signal_all(pids, sig, identities = {})
277
299
  pids.each do |tpid|
278
300
  # Last-moment re-check: a PID recycled after the grace window must
@@ -1,6 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require "logger"
4
3
  require_relative "../log"
5
4
  require_relative "requires_dag"
6
5
 
@@ -2,6 +2,8 @@
2
2
 
3
3
  require "digest"
4
4
 
5
+ require_relative "../errors"
6
+
5
7
  module Rubik
6
8
  module Plugin
7
9
  # Containment + inventory policy for directory plugin packages
@@ -12,7 +14,7 @@ module Rubik
12
14
  # escape the package and special files are not content, so both are
13
15
  # violations — add and verify fail closed on them.
14
16
  module PackageInventory
15
- class Violation < StandardError; end
17
+ class Violation < Rubik::Error; end
16
18
 
17
19
  module_function
18
20
 
@@ -1,6 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require "logger"
4
3
  require_relative "../log"
5
4
 
6
5
  module Rubik
@@ -123,7 +123,11 @@ module Rubik
123
123
  nil
124
124
  end
125
125
  end
126
- rescue StandardError
126
+ rescue StandardError => e
127
+ # Best-effort by design — but the blanket method-level rescue must
128
+ # not hide real bugs in the restore logic itself; the granular
129
+ # rescues above stay silent on purpose.
130
+ Rubik::Log.debug(:repl, "[Repl] console restore after interrupt failed: #{e.class}: #{e.message}")
127
131
  nil
128
132
  end
129
133
  end
@@ -215,7 +215,7 @@ module Rubik
215
215
  begin
216
216
  cleanup.call
217
217
  rescue StandardError => e
218
- Rubik::Log.warn(:repl, "[WARN] Config cleanup failed: #{e.message}")
218
+ Rubik::Log.warn(:repl, "Config cleanup failed: #{e.message}")
219
219
  end
220
220
  end
221
221
  end
@@ -61,14 +61,6 @@ module Rubik
61
61
  synchronize { @inbox.dup }
62
62
  end
63
63
 
64
- def flush_inbox!
65
- synchronize do
66
- items = @inbox.dup
67
- @inbox.clear
68
- items
69
- end
70
- end
71
-
72
64
  def flush_notices!
73
65
  items, reading = synchronize do
74
66
  next [nil, false] if @inbox.empty?
@@ -2,10 +2,11 @@
2
2
 
3
3
  require "monitor"
4
4
  require_relative "../coeffects"
5
+ require_relative "../errors"
5
6
 
6
7
  module Rubik
7
8
  module Runtime
8
- class CoeffectMissingError < StandardError; end
9
+ class CoeffectMissingError < Rubik::Error; end
9
10
 
10
11
  # Raised when a sealed context denies a coeffect lookup by policy.
11
12
  # Subclasses CoeffectMissingError so existing rescue clauses keep
@@ -15,7 +16,7 @@ module Rubik
15
16
  # Raised when a disposed context is asked to create new scope. Unlike a
16
17
  # late inverse (which can run now), there is no meaningful fallback for
17
18
  # extend, so it fails fast (AGENTS.md Fail Fast template).
18
- class ContextDisposedError < StandardError; end
19
+ class ContextDisposedError < Rubik::Error; end
19
20
 
20
21
  class Context
21
22
  attr_reader :parent
@@ -79,7 +79,7 @@ module Rubik
79
79
  [project_commands_dir, global_commands_dir, project_tools_dir, global_tools_dir].each do |dir|
80
80
  FileUtils.mkdir_p(dir)
81
81
  rescue SystemCallError => e
82
- Rubik::Log.warn(:overlay, "[WARN] Failed to create overlay directory #{dir}: #{e.message}") if ENV["RUBIK_DEBUG"]
82
+ Rubik::Log.warn(:overlay, "Failed to create overlay directory #{dir}: #{e.message}") if ENV["RUBIK_DEBUG"]
83
83
  end
84
84
  end
85
85
 
@@ -423,7 +423,7 @@ module Rubik
423
423
  { ok: true, path: file_path, name: clean_name, scope: scope }
424
424
  rescue StandardError => e
425
425
  # Audit 1: surfaced to the caller as ok:false; tool kind logs under RUBIK_DEBUG.
426
- Rubik::Log.warn(:overlay, "[WARN] [OVERLAY] Failed to save #{kind.label} '#{name}' to #{file_path}: #{e.class}: #{e.message}") if kind.debug_warn && ENV["RUBIK_DEBUG"]
426
+ Rubik::Log.warn(:overlay, "[OVERLAY] Failed to save #{kind.label} '#{name}' to #{file_path}: #{e.class}: #{e.message}") if kind.debug_warn && ENV["RUBIK_DEBUG"]
427
427
  { ok: false, error: e.message }
428
428
  end
429
429
 
@@ -554,7 +554,7 @@ module Rubik
554
554
  File.file?(path) && sentinel_content?(File.binread(path))
555
555
  rescue StandardError => e
556
556
  # Audit 1: unreadable => fail-closed (not a sentinel), but traceable.
557
- Rubik::Log.warn(:overlay, "[WARN] [OVERLAY] sentinel check failed for #{path}: #{e.class}: #{e.message}") if ENV["RUBIK_DEBUG"]
557
+ Rubik::Log.warn(:overlay, "[OVERLAY] sentinel check failed for #{path}: #{e.class}: #{e.message}") if ENV["RUBIK_DEBUG"]
558
558
  false
559
559
  end
560
560
 
@@ -29,27 +29,51 @@ module Rubik
29
29
  return probe_failure(proposed_cmd, 127, "Availability check failed: executable not found in PATH")
30
30
  end
31
31
 
32
- if @guard
33
- cmd_to_check = proposed_cmd.is_a?(Hash) ? [proposed_cmd[:executable], *Array(proposed_cmd[:args])].join(" ") : proposed_cmd.to_s
34
- begin
35
- @guard.verify_command_safety!(cmd_to_check)
36
- rescue Rubik::Security::BlockedWriteError => e
37
- return probe_failure(proposed_cmd, 1, "Proposed command blocked by security guard: #{e.message}")
38
- end
32
+ guard_failure = guard_rejection(proposed_cmd)
33
+ return guard_failure if guard_failure
34
+
35
+ return probe_lsp(lang, proposed_cmd, sub_ctx) if target == "lsp"
36
+
37
+ probe_executable(proposed_cmd, sub_ctx, probe_args: probe_args)
38
+ end
39
+
40
+ private
41
+
42
+ # Security-gate phase: run the operator's command guard (when wired)
43
+ # before any probe can spawn. Returns the probe_failure pair on a
44
+ # BlockedWriteError, or nil when the command passed (or no guard is
45
+ # configured).
46
+ def guard_rejection(proposed_cmd)
47
+ return nil unless @guard
48
+
49
+ cmd_to_check = proposed_cmd.is_a?(Hash) ? [proposed_cmd[:executable], *Array(proposed_cmd[:args])].join(" ") : proposed_cmd.to_s
50
+ begin
51
+ @guard.verify_command_safety!(cmd_to_check)
52
+ rescue Rubik::Security::BlockedWriteError => e
53
+ probe_failure(proposed_cmd, 1, "Proposed command blocked by security guard: #{e.message}")
39
54
  end
55
+ end
40
56
 
41
- if target == "lsp"
42
- client = Rubik::LSP::Client.new(lang, root_dir: @root_dir, server_cmd: proposed_cmd)
43
- sub_ctx.on_dispose { client.stop }
44
- begin
45
- result = Timeout.timeout(PROBE_TIMEOUT) { client.start }
46
- return probe_failure(proposed_cmd, 1, "Functional probe failed: LSP initialize handshake rejected") unless result && client.alive?
47
- rescue Timeout::Error
48
- return probe_failure(proposed_cmd, 124, "LSP initialize handshake timed out")
49
- end
50
- return [true, nil]
57
+ # LSP probe phase: a full initialize handshake against the proposed
58
+ # server, hard-capped at PROBE_TIMEOUT. The client's lifetime is bound
59
+ # to the caller's probe context via a dispose inverse, so a rejected or
60
+ # timed-out handshake never leaks a server process.
61
+ def probe_lsp(lang, proposed_cmd, sub_ctx)
62
+ client = Rubik::LSP::Client.new(lang, root_dir: @root_dir, server_cmd: proposed_cmd)
63
+ sub_ctx.on_dispose { client.stop }
64
+ begin
65
+ result = Timeout.timeout(PROBE_TIMEOUT) { client.start }
66
+ return probe_failure(proposed_cmd, 1, "Functional probe failed: LSP initialize handshake rejected") unless result && client.alive?
67
+ rescue Timeout::Error
68
+ return probe_failure(proposed_cmd, 124, "LSP initialize handshake timed out")
51
69
  end
70
+ [true, nil]
71
+ end
52
72
 
73
+ # Executable probe phase for test_runner/linter/command targets: select
74
+ # safe diagnostic probe_args (defaulting known help-capable binaries to
75
+ # --help), then hand the validated argv to the spawn phase.
76
+ def probe_executable(proposed_cmd, sub_ctx, probe_args:)
53
77
  argv = Shellwords.split(proposed_cmd)
54
78
  if probe_args.nil?
55
79
  unless HELP_PROBE_BINARIES.include?(File.basename(argv.first.to_s))
@@ -66,9 +90,16 @@ module Rubik
66
90
  end
67
91
  end
68
92
 
93
+ run_probe_process(argv, probe_args, proposed_cmd, sub_ctx)
94
+ end
95
+
96
+ # Spawn + reap phase: the probe runs array-form so no shell operators
97
+ # are ever interpreted; output goes to a file so no pipe-reader thread
98
+ # survives a timeout or a forked descendant. The kill/reap dispose
99
+ # inverse and the polling loop share the reaped flag, so the process is
100
+ # killed and reaped exactly once whichever side wins the race.
101
+ def run_probe_process(argv, probe_args, proposed_cmd, sub_ctx)
69
102
  argv.concat(probe_args)
70
- # Array-form spawn never interprets shell operators. File-backed output
71
- # avoids pipe-reader threads surviving a timeout or a forked descendant.
72
103
  output = Tempfile.new("rubik-repair-probe")
73
104
  sub_ctx.on_dispose { output.close! }
74
105
  options = { chdir: @root_dir, in: File::NULL, out: output, err: output }
@@ -106,8 +137,6 @@ module Rubik
106
137
  end
107
138
  end
108
139
 
109
- private
110
-
111
140
  def probe_failure(command, code, message)
112
141
  [false, Rubik::Runtime::DiagnosticEngine.diagnose(cmd: command, exit_code: code, stderr: message)]
113
142
  end