rubik 0.15.1 → 0.15.3

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 (55) hide show
  1. checksums.yaml +4 -4
  2. data/ATTRIBUTION.md +1 -1
  3. data/CHANGELOG.md +67 -2
  4. data/lib/rubik/ast/cache_store.rb +22 -4
  5. data/lib/rubik/ast/extractor.rb +1 -4
  6. data/lib/rubik/ast/ruby_extractor.rb +23 -1
  7. data/lib/rubik/ast/symbol.rb +9 -4
  8. data/lib/rubik/ast/treesitter/python_walker.rb +5 -4
  9. data/lib/rubik/ast/treesitter_extractor.rb +10 -3
  10. data/lib/rubik/buffer/diff.rb +34 -2
  11. data/lib/rubik/buffer/manager.rb +18 -15
  12. data/lib/rubik/buffer/path_validator.rb +18 -2
  13. data/lib/rubik/buffer/snapshot.rb +144 -9
  14. data/lib/rubik/concurrency/timers.rb +7 -0
  15. data/lib/rubik/config/scoped.rb +18 -7
  16. data/lib/rubik/config/secret_policy.rb +22 -1
  17. data/lib/rubik/config.rb +24 -26
  18. data/lib/rubik/context/ignore_rules.rb +7 -2
  19. data/lib/rubik/diagnostics/parser.rb +19 -8
  20. data/lib/rubik/kernel/dispatcher.rb +11 -5
  21. data/lib/rubik/llm/client.rb +24 -3
  22. data/lib/rubik/llm/connection_pool.rb +51 -30
  23. data/lib/rubik/llm/message_sanitizer.rb +20 -1
  24. data/lib/rubik/llm/sse_parser.rb +10 -1
  25. data/lib/rubik/lsp/client.rb +9 -2
  26. data/lib/rubik/lsp/manager.rb +43 -40
  27. data/lib/rubik/lsp/transport.rb +61 -1
  28. data/lib/rubik/mcp/transport/stdio.rb +143 -131
  29. data/lib/rubik/orchestrator/activity_log.rb +3 -2
  30. data/lib/rubik/orchestrator/goal_session.rb +14 -14
  31. data/lib/rubik/orchestrator/loop.rb +11 -12
  32. data/lib/rubik/orchestrator/subagent/completion.rb +18 -8
  33. data/lib/rubik/orchestrator/turn_executor/user_channel.rb +5 -1
  34. data/lib/rubik/platform/process.rb +74 -19
  35. data/lib/rubik/platform.rb +16 -16
  36. data/lib/rubik/plugin/manager.rb +5 -6
  37. data/lib/rubik/repl/service_catalog.rb +1 -1
  38. data/lib/rubik/repl/terminal_guard.rb +29 -23
  39. data/lib/rubik/repl/turn_recorder.rb +35 -11
  40. data/lib/rubik/sandbox/driver/base.rb +26 -3
  41. data/lib/rubik/sandbox/driver/bubblewrap.rb +6 -11
  42. data/lib/rubik/sandbox/driver/docker.rb +1 -11
  43. data/lib/rubik/sandbox/driver/podman.rb +26 -18
  44. data/lib/rubik/sandbox/driver/process.rb +16 -35
  45. data/lib/rubik/security/blocked_guidance.rb +4 -2
  46. data/lib/rubik/security/command_gate.rb +27 -14
  47. data/lib/rubik/security/errors.rb +13 -0
  48. data/lib/rubik/security/guard.rb +11 -2
  49. data/lib/rubik/security/path_policy.rb +9 -6
  50. data/lib/rubik/storage/store.rb +31 -11
  51. data/lib/rubik/tools/builtins/exec.rb +5 -1
  52. data/lib/rubik/tools/builtins/files.rb +2 -0
  53. data/lib/rubik/tools/uri_resolver.rb +23 -3
  54. data/lib/rubik/version.rb +1 -1
  55. metadata +1 -1
@@ -10,11 +10,24 @@ require_relative "../platform"
10
10
  module Rubik
11
11
  module Buffer
12
12
  class Snapshot
13
- attr_reader :id, :timestamp, :files
13
+ # JSON cannot emit invalid UTF-8, so binary buffer contents are tagged
14
+ # and hex-encoded before deflate (issue #628 + #629).
15
+ BINARY_MARKER = "__rubik_binary_hex_v1__"
16
+ HEX_PATTERN = /\A(?:[0-9a-fA-F]{2})*\z/
17
+ # A persisted snapshot is loaded synchronously at startup. Bound the
18
+ # inflate output so a small malicious file cannot exhaust memory.
19
+ MAX_SNAPSHOT_BYTES = 8 * 1024 * 1024
20
+ INFLATE_CHUNK_BYTES = 64 * 1024
14
21
 
15
- def initialize(id: nil, timestamp: nil, files: {})
22
+ attr_reader :id, :timestamp, :files, :created_at
23
+
24
+ def initialize(id: nil, timestamp: nil, files: {}, created_at: nil)
25
+ now = Time.now
16
26
  @id = id || SecureRandom.hex(6)
17
- @timestamp = timestamp || Time.now.to_i
27
+ @timestamp = timestamp || now.to_i
28
+ # Sub-second creation time orders undo steps made in the same second
29
+ # (issue #629); older files without it fall back to their timestamp.
30
+ @created_at = created_at || (timestamp ? timestamp.to_f : now.to_f)
18
31
  @files = files
19
32
  end
20
33
 
@@ -22,6 +35,7 @@ module Rubik
22
35
  {
23
36
  "id" => @id,
24
37
  "timestamp" => @timestamp,
38
+ "created_at" => @created_at,
25
39
  "files" => @files
26
40
  }
27
41
  end
@@ -30,17 +44,61 @@ module Rubik
30
44
  new(
31
45
  id: hash["id"],
32
46
  timestamp: hash["timestamp"],
47
+ created_at: hash["created_at"],
33
48
  files: hash["files"] || {}
34
49
  )
35
50
  end
36
51
 
37
52
  def compress
38
- Zlib::Deflate.deflate(JSON.dump(to_h))
53
+ payload = to_h
54
+ payload["files"] = @files.transform_values { |content| encode_file_content(content) }
55
+ Zlib::Deflate.deflate(JSON.dump(payload))
39
56
  end
40
57
 
41
58
  def self.decompress(binary_data)
42
- decompressed = Zlib::Inflate.inflate(binary_data)
43
- from_h(JSON.parse(decompressed))
59
+ inflater = Zlib::Inflate.new
60
+ out = +"".b
61
+ begin
62
+ offset = 0
63
+ until inflater.finished? || offset >= binary_data.bytesize
64
+ chunk = binary_data.byteslice(offset, INFLATE_CHUNK_BYTES)
65
+ offset += chunk.bytesize
66
+ out << inflater.inflate(chunk)
67
+ raise Zlib::DataError, "snapshot exceeds #{MAX_SNAPSHOT_BYTES} bytes" if out.bytesize > MAX_SNAPSHOT_BYTES
68
+ end
69
+ loop do
70
+ tail = inflater.inflate("")
71
+ break if tail.empty? || inflater.finished?
72
+
73
+ out << tail
74
+ raise Zlib::DataError, "snapshot exceeds #{MAX_SNAPSHOT_BYTES} bytes" if out.bytesize > MAX_SNAPSHOT_BYTES
75
+ end
76
+ raise Zlib::DataError, "snapshot stream is truncated" unless inflater.finished?
77
+ ensure
78
+ inflater.close
79
+ end
80
+
81
+ payload = JSON.parse(out)
82
+ payload["files"] = (payload["files"] || {}).transform_values { |value| decode_file_content(value) }
83
+ from_h(payload)
84
+ end
85
+
86
+ def encode_file_content(content)
87
+ return content unless content.is_a?(String)
88
+ return content if content.encoding == Encoding::UTF_8 && content.valid_encoding?
89
+
90
+ # Binary-tagged content can still hold valid UTF-8 bytes. Hex-tag it
91
+ # too so JSON.dump never re-encodes it and the encoding round-trips.
92
+ { BINARY_MARKER => content.b.unpack1("H*") }
93
+ end
94
+
95
+ def self.decode_file_content(value)
96
+ return value unless value.is_a?(Hash) && value.key?(BINARY_MARKER)
97
+
98
+ hex = value[BINARY_MARKER]
99
+ return value unless hex.is_a?(String) && hex.match?(HEX_PATTERN)
100
+
101
+ [hex].pack("H*").force_encoding(Encoding::BINARY)
44
102
  end
45
103
  end
46
104
 
@@ -49,8 +107,9 @@ module Rubik
49
107
 
50
108
  # Issue #589: in-memory snapshots stay per-edit (undo granularity is
51
109
  # untouched), but the whole-buffer deflate+disk persist is debounced to
52
- # at most one write per interval — the IO is the expensive part and the
53
- # files are durability artifacts, never read back by undo/rollback.
110
+ # at most one write per interval — the IO is the expensive part. The
111
+ # files are durability artifacts: load_snapshots restores them at
112
+ # startup so undo/rollback survive a restart (issue #629).
54
113
  # 0 disables debouncing (the historical per-write persistence, still
55
114
  # the default so standalone/test stores keep exact per-edit durability).
56
115
  DEFAULT_MIN_INTERVAL = 0.0
@@ -59,6 +118,9 @@ module Rubik
59
118
  # tail). Keeps a long session from accumulating unbounded snapshot
60
119
  # files (issue #589).
61
120
  DEFAULT_MAX_SNAPSHOTS = 200
121
+ # Ids minted by Snapshot#initialize are SecureRandom.hex(6). Refuse any
122
+ # other shape on load so a crafted .zdeflate cannot steer file deletion.
123
+ SNAPSHOT_ID_PATTERN = /\A[0-9a-f]{12}\z/
62
124
 
63
125
  def initialize(storage_dir: File.join(Rubik::Platform.home_dir, ".rubik", "snapshots", "default"),
64
126
  min_interval: DEFAULT_MIN_INTERVAL,
@@ -91,6 +153,43 @@ module Rubik
91
153
  end
92
154
  end
93
155
 
156
+ # Restores persisted snapshots so undo/rollback work after a restart
157
+ # (issue #629). Called once from the composition root at startup.
158
+ # Defensive: a corrupt or incompatible file is skipped with a warning,
159
+ # never allowed to break buffer startup. Idempotent.
160
+ #
161
+ # @return [Integer] number of snapshots restored
162
+ def load_snapshots
163
+ @monitor.synchronize do
164
+ return @snapshots.size if @snapshots.any?
165
+
166
+ entries = Dir.glob(File.join(@storage_dir, "*.zdeflate")).filter_map do |path|
167
+ snapshot = load_snapshot_file(path)
168
+ [path, snapshot] if snapshot
169
+ end
170
+ # Second-resolution timestamps tie for rapid edits and glob order
171
+ # follows random hex ids. created_at carries sub-second precision.
172
+ # Every loaded value is validated numeric by load_snapshot_file, so
173
+ # one malformed file can never abort startup here.
174
+ entries.sort_by! { |_path, snapshot| [snapshot.created_at, snapshot.timestamp] }
175
+
176
+ excess = entries.size - @max_snapshots
177
+ if excess.positive?
178
+ dropped = entries.shift(excess)
179
+ dropped.each do |entry|
180
+ path = entry[0]
181
+ File.delete(path)
182
+ rescue SystemCallError => e
183
+ warn "[Buffer] could not remove excess snapshot #{safe_basename(path)}: #{e.class}"
184
+ end
185
+ end
186
+
187
+ @snapshots = entries.map { |_path, snapshot| snapshot }
188
+ @current_index = @snapshots.empty? ? -1 : @snapshots.size - 1
189
+ @snapshots.size
190
+ end
191
+ end
192
+
94
193
  def create_snapshot(buffer_manager)
95
194
  @monitor.synchronize do
96
195
  return nil unless buffer_manager.dirty?
@@ -148,7 +247,8 @@ module Rubik
148
247
  @current_index -= excess
149
248
  @current_index = -1 if @current_index.negative?
150
249
  dropped.each do |snapshot|
151
- File.delete(File.join(@storage_dir, "#{snapshot.id}.zdeflate"))
250
+ path = snapshot_file_path(snapshot.id)
251
+ File.delete(path) if path
152
252
  rescue SystemCallError
153
253
  nil
154
254
  end
@@ -182,6 +282,41 @@ module Rubik
182
282
  true
183
283
  end
184
284
  end
285
+
286
+ private
287
+
288
+ def load_snapshot_file(path)
289
+ snapshot = Snapshot.decompress(File.binread(path))
290
+ return nil unless snapshot.is_a?(Snapshot) && snapshot.files.is_a?(Hash)
291
+ return nil unless snapshot.id.is_a?(String) && snapshot.id.match?(SNAPSHOT_ID_PATTERN)
292
+ return nil unless snapshot.created_at.is_a?(Numeric) && snapshot.timestamp.is_a?(Numeric)
293
+ return nil unless snapshot.files.all? { |key, value| key.is_a?(String) && value.is_a?(String) }
294
+
295
+ snapshot
296
+ rescue StandardError => e
297
+ warn "[Buffer] skipping unreadable snapshot #{safe_basename(path)}: #{e.class}: #{safe_message(e)}"
298
+ nil
299
+ end
300
+
301
+ # Deletion target for a loaded id: valid shape, resolved under the
302
+ # storage root. Returns nil for anything else (defense in depth).
303
+ def snapshot_file_path(id)
304
+ return nil unless id.is_a?(String) && id.match?(SNAPSHOT_ID_PATTERN)
305
+
306
+ path = File.expand_path(File.join(@storage_dir, "#{id}.zdeflate"))
307
+ root = File.expand_path(@storage_dir) + File::SEPARATOR
308
+ path if path.start_with?(root)
309
+ end
310
+
311
+ # Snapshot filenames/messages are attacker-influenced; strip control
312
+ # chars so a crafted file cannot forge or repaint a warning line.
313
+ def safe_basename(path)
314
+ File.basename(path.to_s).gsub(/[[:cntrl:]]/, "?")[0, 120]
315
+ end
316
+
317
+ def safe_message(error)
318
+ error.message.to_s.gsub(/[[:cntrl:]]/, " ")[0, 200]
319
+ end
185
320
  end
186
321
  end
187
322
  end
@@ -91,7 +91,14 @@ module Rubik
91
91
  def prune!
92
92
  return unless @staleness
93
93
 
94
+ before = @heap.size
94
95
  @heap.reject! { |entry| @staleness.call(entry[1], entry[3]) }
96
+ return if @heap.size == before || @heap.empty?
97
+
98
+ # reject! compacts the array but does not preserve the heap property:
99
+ # a stale root leaves its former child at index 0, which is not the
100
+ # minimum. Rebuild bottom-up so next_gap/fire_due! can trust @heap[0].
101
+ ((@heap.size / 2) - 1).downto(0) { |index| sift_down(index) }
95
102
  end
96
103
 
97
104
  def sift_up(index)
@@ -65,7 +65,10 @@ module Rubik
65
65
  def set(key, value, persist: nil)
66
66
  raise ArgumentError, "Scoped child configurations cannot persist to disk (scope: #{persist.inspect})" if persisting?(persist)
67
67
 
68
- @monitor.synchronize do
68
+ should_notify = false
69
+ new_val = nil
70
+ old_val = nil
71
+ res = @monitor.synchronize do
69
72
  old_val = fetch(key)
70
73
  typed_val = parse_scalar_value(value)
71
74
  typed_val = Schema.coerce(key, typed_val)
@@ -77,24 +80,32 @@ module Rubik
77
80
  validate_schema(typed_val, section, key.to_s) if section.is_a?(Hash) && !section.empty?
78
81
  end
79
82
  deep_set_key(@overrides, key, typed_val)
80
- notify_change(key, typed_val, old_val) if old_val != typed_val
83
+ should_notify = old_val != typed_val
84
+ new_val = typed_val
81
85
  { ok: true }
82
86
  end
87
+ notify_change(key, new_val, old_val) if should_notify
88
+ res
83
89
  end
84
90
 
85
91
  def delete(key, persist: nil)
86
92
  raise ArgumentError, "Scoped child configurations cannot persist to disk" if persisting?(persist)
87
93
 
88
- @monitor.synchronize do
94
+ should_notify = false
95
+ new_val = nil
96
+ old_val = nil
97
+ res = @monitor.synchronize do
89
98
  old_val = fetch(key)
90
99
  deep_delete(@overrides, key)
91
100
  new_val = fetch(key)
92
- if old_val != new_val
93
- notify_change(key, new_val, old_val)
94
- @event_bus&.emit(:config_deleted, key: key.to_s, old_val: old_val)
95
- end
101
+ should_notify = old_val != new_val
96
102
  { ok: true }
97
103
  end
104
+ if should_notify
105
+ notify_change(key, new_val, old_val)
106
+ @event_bus&.emit(:config_deleted, key: key.to_s, old_val: redact_secret_value(key, old_val))
107
+ end
108
+ res
98
109
  end
99
110
 
100
111
  def model_spec(role = :default)
@@ -2,6 +2,7 @@
2
2
 
3
3
  require_relative "../log"
4
4
  require_relative "../security/secret_store"
5
+ require_relative "../security/redactor"
5
6
 
6
7
  module Rubik
7
8
  class Config
@@ -29,6 +30,7 @@ module Rubik
29
30
  # Dot-paths that end in an api_key leaf, e.g.
30
31
  # "providers.openai.api_key" or a bare "api_key".
31
32
  SECRET_LEAF_PATTERN = /\A(?:[\w-]+\.)*api_key\z/
33
+ REDACTED_VALUE = "[REDACTED]"
32
34
 
33
35
  module_function
34
36
 
@@ -36,6 +38,25 @@ module Rubik
36
38
  key.to_s.match?(SECRET_LEAF_PATTERN)
37
39
  end
38
40
 
41
+ # Mask secret-bearing values before they leave Config in an event.
42
+ # Covers a direct api_key leaf and nested hashes from whole-provider
43
+ # writes; non-secret values pass through so ordinary events are intact.
44
+ def redact_secret_value(key, value)
45
+ return value if value.nil?
46
+ return REDACTED_VALUE if secret_key?(key)
47
+
48
+ case value
49
+ when Hash
50
+ value.each_with_object({}) do |(child_key, child_val), out|
51
+ out[child_key] = redact_secret_value(child_key, child_val)
52
+ end
53
+ when Array
54
+ value.map { |item| redact_secret_value(key, item) }
55
+ else
56
+ value
57
+ end
58
+ end
59
+
39
60
  # Store-name convention shared by the write guard and `!secrets
40
61
  # migrate`: project-scope secrets get a ".project"-suffixed name so a
41
62
  # project-scoped credential can never silently overwrite (or be
@@ -196,7 +217,7 @@ module Rubik
196
217
  def warn_secret_store_fallback(error, scope)
197
218
  msg = "OS secret store unavailable (#{error.message}); plaintext kept in #{scope} config"
198
219
  @warnings << msg
199
- Rubik::Log.warn(:config, "[WARN] #{msg}") if ENV["RUBIK_DEBUG"]
220
+ Rubik::Log.warn(:config, "[WARN] #{msg}")
200
221
  end
201
222
 
202
223
  def plaintext_fallback_info
data/lib/rubik/config.rb CHANGED
@@ -77,7 +77,7 @@ module Rubik
77
77
  # {ok: false, error:, reason: :persist_failed} when the write failed —
78
78
  # so callers report honestly instead of assuming success.
79
79
  def set(key, value, persist: nil)
80
- @monitor.synchronize do
80
+ res, old_val, new_val = @monitor.synchronize do
81
81
  old_val = fetch(key)
82
82
  typed_val = parse_scalar_value(value)
83
83
  typed_val = Schema.coerce(key, typed_val)
@@ -110,28 +110,21 @@ module Rubik
110
110
  res = persisting?(persist) ? persist_result(save!(persist)) : { ok: true }
111
111
  res[:reason] = :persist_failed unless res[:ok]
112
112
  res[:secret] = policy[:info] if policy&.key?(:info)
113
- notify_change(key, typed_val, old_val) if old_val != typed_val
114
- res
113
+ [res, old_val, typed_val]
115
114
  end
115
+ # Outside @monitor (#623); concurrent notifications may reorder — serializing them would reintroduce the deadlock.
116
+ notify_change(key, new_val, old_val) if old_val != new_val
117
+ res
116
118
  end
117
119
 
118
120
  # Sets a temporary configuration change within a Context lifecycle (AGENTS.md Ω).
119
121
  # When ctx is disposed, the inverse restores the prior configuration value.
120
122
  def set_revertible(ctx, key, new_val)
121
- @monitor.synchronize do
122
- old_val = fetch(key)
123
- had_key = !old_val.nil?
124
- set(key, new_val, persist: nil)
125
- return unless ctx.respond_to?(:on_dispose)
126
-
127
- ctx.on_dispose do
128
- if had_key
129
- set(key, old_val, persist: nil)
130
- else
131
- delete(key, persist: nil)
132
- end
133
- end
134
- end
123
+ old_val = @monitor.synchronize { fetch(key) }
124
+ set(key, new_val, persist: nil)
125
+ return unless ctx.respond_to?(:on_dispose)
126
+
127
+ ctx.on_dispose { old_val.nil? ? delete(key, persist: nil) : set(key, old_val, persist: nil) }
135
128
  end
136
129
 
137
130
  # Creates an isolated, scoped child configuration (AGENTS.md Unified Context).
@@ -144,7 +137,7 @@ module Rubik
144
137
  # Deleting an absent key is a successful no-op. Returns the persist
145
138
  # outcome (see set); notifies listeners on change.
146
139
  def delete(key, persist: nil)
147
- @monitor.synchronize do
140
+ res, old_val, new_val = @monitor.synchronize do
148
141
  old_val = fetch(key)
149
142
  blocked = deep_delete(@data, key) == :blocked
150
143
  return { ok: false, error: "cannot delete '#{key}': path traverses a non-hash value" } if blocked
@@ -163,13 +156,14 @@ module Rubik
163
156
  res[:reason] = :persist_failed unless res[:ok]
164
157
 
165
158
  new_val = fetch(key)
166
- if old_val != new_val
167
- notify_change(key, new_val, old_val)
168
- @event_bus&.emit(:config_deleted, key: key.to_s, old_val: old_val)
169
- end
170
159
  cleanup_stored_secret(key, res, persist, old_val: old_val)
171
- res
160
+ [res, old_val, new_val]
161
+ end
162
+ if old_val != new_val
163
+ notify_change(key, new_val, old_val)
164
+ @event_bus&.emit(:config_deleted, key: key.to_s, old_val: redact_secret_value(key, old_val))
172
165
  end
166
+ res
173
167
  end
174
168
 
175
169
  # True only for scopes save! writes to disk; nil/false/:session/"session"/
@@ -254,11 +248,15 @@ module Rubik
254
248
  begin
255
249
  entry[:callback].call(key_str, new_val, old_val)
256
250
  rescue StandardError => e
257
- Rubik::Log.warn(:config, "[WARN] Config listener failed for '#{key_str}': #{e.message}")
258
- @event_bus&.emit(:config_listener_error, key: key_str, error: e.message)
251
+ # A listener error may quote a nested secret even on a non-secret key (#622).
252
+ error_text = secret_key?(key_str) ? SecretPolicy::REDACTED_VALUE : Rubik::Security::Redactor.redact(e.message.to_s)
253
+ Rubik::Log.warn(:config, "[WARN] Config listener failed for '#{key_str}': #{error_text}")
254
+ @event_bus&.emit(:config_listener_error, key: key_str, error: error_text)
259
255
  end
260
256
  end
261
- @event_bus&.emit(:config_changed, key: key_str, value: new_val, old_val: old_val)
257
+ safe_new = redact_secret_value(key_str, new_val)
258
+ safe_old = redact_secret_value(key_str, old_val)
259
+ @event_bus&.emit(:config_changed, key: key_str, value: safe_new, old_val: safe_old)
262
260
  end
263
261
 
264
262
  def recompute_data!
@@ -88,7 +88,10 @@ module Rubik
88
88
  @prunable_needles = @patterns.filter_map do |pattern|
89
89
  next unless (m = PRUNABLE_PATTERN.match(pattern))
90
90
 
91
- m[1].split("/")
91
+ stem = m[1]
92
+ # A leading "/" anchors the ignore to the scan root; an unanchored
93
+ # stem (including the "**/" prefix) matches at any depth.
94
+ [stem.delete_prefix("/").split("/"), stem.start_with?("/")]
92
95
  end.freeze
93
96
  @file_regexes = compile(@patterns).freeze
94
97
  # The git fast path skips prunable subtree patterns with literal
@@ -107,7 +110,9 @@ module Rubik
107
110
  def prune_dir?(rel_comps)
108
111
  return true if HARD_PRUNE_ROOTS.include?(rel_comps.first)
109
112
 
110
- @prunable_needles.any? { |needle| contiguous_components?(rel_comps, needle) }
113
+ @prunable_needles.any? do |needle, anchored|
114
+ anchored ? rel_comps[0, needle.size] == needle : contiguous_components?(rel_comps, needle)
115
+ end
111
116
  end
112
117
 
113
118
  # Walker-dialect file filter: reserved roots plus every ignore pattern
@@ -5,6 +5,12 @@ require_relative "entry"
5
5
  module Rubik
6
6
  module Diagnostics
7
7
  class Parser
8
+ # Match the FIRST ":line:col:" so a location mentioned inside the
9
+ # diagnostic message cannot be mistaken for the file location. The
10
+ # message tail is outside the matched portion, so colon-heavy input
11
+ # cannot trigger catastrophic backtracking (CodeQL ReDoS).
12
+ GO_DIAGNOSTIC = /^(\S+?):(\d+):(\d+):(.*)$/m
13
+
8
14
  def self.parse(output, lang = :unknown)
9
15
  new.parse(output, lang)
10
16
  end
@@ -51,15 +57,20 @@ module Rubik
51
57
  end
52
58
 
53
59
  def parse_go(text)
54
- entries = []
55
- text.each_line do |line|
56
- next unless (m = line.match(/^([^:]+):(\d+):(\d+):(.*)$/))
57
-
58
- msg = m[4].strip
59
- cat = msg.start_with?("undefined:") ? :undefined_ref : :syntax
60
- entries << Entry.new(file: m[1], line: m[2], col: m[3], message: msg, category: cat, raw_text: line)
60
+ text.each_line.filter_map do |line|
61
+ parts = go_diagnostic_parts(line.chomp)
62
+ next unless parts
63
+
64
+ file, line_no, col, msg = parts
65
+ category = msg.start_with?("undefined:") ? :undefined_ref : :syntax
66
+ Entry.new(file: file, line: line_no, col: col, message: msg,
67
+ category: category, raw_text: line)
61
68
  end
62
- entries
69
+ end
70
+
71
+ def go_diagnostic_parts(text)
72
+ m = GO_DIAGNOSTIC.match(text)
73
+ m && [m[1], m[2], m[3], m[4].strip]
63
74
  end
64
75
 
65
76
  def parse_rust(text)
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "monitor"
4
+ require_relative "../config/secret_policy"
4
5
 
5
6
  module Rubik
6
7
  module Kernel
@@ -144,12 +145,14 @@ module Rubik
144
145
  def invoke_listener(listener, event)
145
146
  listener.arity.zero? ? listener.call : listener.call(event.payload)
146
147
  rescue StandardError => e
148
+ # A subscriber may raise with a fetched secret in the message (#622).
149
+ safe_msg = Rubik::Security::Redactor.redact(e.message.to_s)
147
150
  begin
148
- @dmesg&.log(:kernel, :err, "Subscriber error on #{event.name}: #{e.class}: #{e.message}")
151
+ @dmesg&.log(:kernel, :err, "Subscriber error on #{event.name}: #{e.class}: #{safe_msg}")
149
152
  rescue StandardError
150
153
  nil
151
154
  end
152
- @logger&.error("EventBus subscriber error on event '#{event.name}': #{e.class}: #{e.message}")
155
+ @logger&.error("EventBus subscriber error on event '#{event.name}': #{e.class}: #{safe_msg}")
153
156
  end
154
157
 
155
158
  def log_to_dmesg(event)
@@ -157,9 +160,12 @@ module Rubik
157
160
 
158
161
  data = event.payload.is_a?(Hash) ? event.payload.dup : { value: event.payload }
159
162
  fac_id = data.delete(:facility_id) || event.facility_id
160
- safe_data = {}
161
- data.each do |k, v|
162
- safe_data[k.to_sym] = v
163
+ # Defense in depth (#622): never copy a raw secret into dmesg.
164
+ secret = Rubik::Config::SecretPolicy.secret_key?(data[:key] || data["key"])
165
+ safe_data = data.each_with_object({}) do |(k, v), out|
166
+ key = k.to_sym
167
+ redact = (secret && [:value, :old_val, :new_val, :error].include?(key)) || Rubik::Config::SecretPolicy.secret_key?(k)
168
+ out[key] = redact ? Rubik::Config::SecretPolicy::REDACTED_VALUE : v
163
169
  rescue StandardError
164
170
  nil
165
171
  end
@@ -5,6 +5,7 @@ require "json"
5
5
  require "time"
6
6
  require "uri"
7
7
  require_relative "../platform"
8
+ require_relative "../security/redactor"
8
9
  require_relative "sse_parser"
9
10
  require_relative "connection_pool"
10
11
 
@@ -76,6 +77,11 @@ module Rubik
76
77
  # interactive agent turn indefinitely.
77
78
  RATE_LIMIT_MAX_DELAY_S = 60
78
79
 
80
+ # Issue #634: provider bodies are untrusted and can carry prompts, tool
81
+ # arguments or credentials. Exception messages embed a bounded, redacted
82
+ # preview by default; the verbatim body is opt-in via RUBIK_DEBUG.
83
+ MAX_ERROR_BODY_CHARS = 512
84
+
79
85
  # Retry knobs that may be supplied per call (resolved from llm.* config
80
86
  # by the orchestrator seams) and forwarded to post_json. Only keys that
81
87
  # are explicitly present are forwarded: passing nil would break the
@@ -128,6 +134,21 @@ module Rubik
128
134
  delay.clamp(0, max_delay)
129
135
  end
130
136
 
137
+ # Bounded, redacted representation of a provider error body for an
138
+ # exception message (issue #634). The shared Redactor is the SSOT for
139
+ # secret masking; RUBIK_DEBUG opts back into the full body for diagnosis.
140
+ def self.error_body_detail(body)
141
+ text = Rubik::Platform.safe_utf8(body).to_s
142
+ return text if ENV["RUBIK_DEBUG"]
143
+ return text if text.empty?
144
+
145
+ redacted = Rubik::Security::Redactor.redact(text)
146
+ return redacted if redacted.length <= MAX_ERROR_BODY_CHARS
147
+
148
+ "#{redacted[0, MAX_ERROR_BODY_CHARS]}… (truncated #{redacted.length - MAX_ERROR_BODY_CHARS} chars; " \
149
+ "set RUBIK_DEBUG for full body)"
150
+ end
151
+
131
152
  # `retries` is nil on paths that never entered the retry loop (streaming)
132
153
  # — the message then omits the attempt count instead of falsely claiming
133
154
  # "gave up after 0 retries" (fresh-eye R5).
@@ -142,7 +163,7 @@ module Rubik
142
163
  detail = hint ? "server hinted #{hint}s" : "no Retry-After hint"
143
164
  budget = retries ? " (gave up after #{retries} rate-limit retries)" : ""
144
165
  RateLimitError.new(
145
- "HTTP 429 rate limited#{budget}, #{detail}: #{Rubik::Platform.safe_utf8(body || res.body)}",
166
+ "HTTP 429 rate limited#{budget}, #{detail}: #{error_body_detail(body || res.body)}",
146
167
  retry_after: hint
147
168
  )
148
169
  end
@@ -214,7 +235,7 @@ module Rubik
214
235
  def self.parse_json_response(res, uri:, status:)
215
236
  unless status >= 200 && status < 300
216
237
  raise ClientError.new(
217
- "HTTP Request failed with code #{res.code}: #{Rubik::Platform.safe_utf8(res.body)}",
238
+ "HTTP Request failed with code #{res.code}: #{error_body_detail(res.body)}",
218
239
  transient: status >= 500
219
240
  )
220
241
  end
@@ -394,7 +415,7 @@ module Rubik
394
415
  # Same status-decided split as the batch path (issue #106):
395
416
  # exhausted 5xx → transient, 4xx → permanent.
396
417
  raise ClientError.new(
397
- "HTTP Request failed with code #{status_code}: #{Rubik::Platform.safe_utf8(body_chunks.join)}",
418
+ "HTTP Request failed with code #{status_code}: #{error_body_detail(body_chunks.join)}",
398
419
  transient: status_code >= 500
399
420
  )
400
421
  end