rubik 0.14.0 → 0.15.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.
Files changed (65) hide show
  1. checksums.yaml +4 -4
  2. data/ATTRIBUTION.md +1 -1
  3. data/CHANGELOG.md +89 -1
  4. data/lib/rubik/adapter/node.rb +4 -1
  5. data/lib/rubik/ast/fallback_cleaner.rb +6 -1
  6. data/lib/rubik/ast/ruby_extractor.rb +12 -6
  7. data/lib/rubik/buffer/manager.rb +15 -10
  8. data/lib/rubik/buffer/snapshot.rb +103 -35
  9. data/lib/rubik/config/scoped.rb +12 -5
  10. data/lib/rubik/connect/models_dev.rb +4 -2
  11. data/lib/rubik/connect/wizard.rb +9 -1
  12. data/lib/rubik/diagnostics/collector.rb +25 -2
  13. data/lib/rubik/llm/client.rb +19 -0
  14. data/lib/rubik/llm/connection_pool.rb +7 -1
  15. data/lib/rubik/llm/formatter.rb +8 -2
  16. data/lib/rubik/llm/router.rb +8 -0
  17. data/lib/rubik/lsp/client.rb +233 -18
  18. data/lib/rubik/lsp/document_store.rb +6 -0
  19. data/lib/rubik/lsp/manager.rb +14 -0
  20. data/lib/rubik/lsp/transport.rb +17 -0
  21. data/lib/rubik/orchestrator/continuation_manager.rb +54 -2
  22. data/lib/rubik/orchestrator/goal_session.rb +10 -10
  23. data/lib/rubik/orchestrator/goal_wait.rb +15 -9
  24. data/lib/rubik/orchestrator/loop.rb +31 -28
  25. data/lib/rubik/orchestrator/subagent/instance.rb +22 -4
  26. data/lib/rubik/orchestrator/subagent/lifecycle.rb +25 -25
  27. data/lib/rubik/orchestrator/subagent/messaging.rb +5 -1
  28. data/lib/rubik/orchestrator/subagent/narration.rb +2 -1
  29. data/lib/rubik/orchestrator/subagent/notices.rb +6 -2
  30. data/lib/rubik/orchestrator/subagent/questioner.rb +42 -4
  31. data/lib/rubik/orchestrator/subagent/reaper.rb +50 -19
  32. data/lib/rubik/orchestrator/subagent/supervisor.rb +11 -0
  33. data/lib/rubik/orchestrator/tool_call_id.rb +8 -4
  34. data/lib/rubik/orchestrator/turn_executor/subagent_channel.rb +21 -5
  35. data/lib/rubik/orchestrator/turn_executor/user_channel.rb +15 -2
  36. data/lib/rubik/platform/process.rb +32 -7
  37. data/lib/rubik/platform/sanitize.rb +17 -18
  38. data/lib/rubik/platform.rb +27 -0
  39. data/lib/rubik/plugin/storage.rb +17 -11
  40. data/lib/rubik/prompt/doctrine.rb +3 -2
  41. data/lib/rubik/repl/commands/base.rb +7 -3
  42. data/lib/rubik/repl/commands/buffer.rb +6 -2
  43. data/lib/rubik/repl/commands/session.rb +11 -1
  44. data/lib/rubik/repl/input_execution.rb +3 -3
  45. data/lib/rubik/repl/service_catalog.rb +6 -2
  46. data/lib/rubik/repl/turn_recorder.rb +4 -1
  47. data/lib/rubik/runtime/manifest_store.rb +7 -2
  48. data/lib/rubik/runtime/task_manager.rb +13 -10
  49. data/lib/rubik/sandbox/driver/base.rb +34 -0
  50. data/lib/rubik/sandbox/driver/bubblewrap.rb +2 -0
  51. data/lib/rubik/sandbox/driver/docker.rb +8 -0
  52. data/lib/rubik/sandbox/driver/podman.rb +8 -0
  53. data/lib/rubik/sandbox/driver/process.rb +9 -12
  54. data/lib/rubik/security/path_policy.rb +28 -3
  55. data/lib/rubik/session/recorder.rb +14 -2
  56. data/lib/rubik/storage/store.rb +7 -0
  57. data/lib/rubik/tools/builtins/exec.rb +7 -1
  58. data/lib/rubik/tools/builtins/interactive.rb +5 -2
  59. data/lib/rubik/tools/builtins/lsp.rb +28 -2
  60. data/lib/rubik/tools/builtins/send_message.rb +7 -2
  61. data/lib/rubik/tools/preflight_runner.rb +4 -1
  62. data/lib/rubik/ui/dialog.rb +5 -1
  63. data/lib/rubik/ui/renderer.rb +4 -1
  64. data/lib/rubik/version.rb +1 -1
  65. metadata +1 -1
@@ -50,6 +50,7 @@ module Rubik
50
50
  pid = nil
51
51
  watchdog = nil
52
52
  deadline_hit = false
53
+ timed_out = false
53
54
 
54
55
  begin
55
56
  Open3.popen3(*, chdir: chdir) do |stdin, stdout, stderr, wait_thr|
@@ -65,12 +66,31 @@ module Rubik
65
66
  # Cancelled in the inner ensure to keep the watchdog from firing
66
67
  # into a recycled pid after normal exit.
67
68
  watchdog = Thread.new(pid, timeout.to_f) do |w_pid, w_deadline|
68
- sleep w_deadline
69
- deadline_hit = true
70
- kill_tree(w_pid)
71
- rescue StandardError
72
- deadline_hit = true
73
- nil
69
+ slept = false
70
+ begin
71
+ sleep w_deadline
72
+ slept = true
73
+ # Race guard (issue #597): only flag a timeout when the kill
74
+ # actually targets a still-live process — a child that completes
75
+ # exactly as the deadline fires keeps its real exit status
76
+ # instead of being relabeled exit 124.
77
+ deadline_hit = true if process_alive?(w_pid)
78
+ kill_tree(w_pid)
79
+ rescue StandardError => e
80
+ # Issue #597-2 follow-up: a kill-path failure at the deadline
81
+ # must never silently drop the timeout — the deadline has
82
+ # fired, so mark it (the caller below raises Timeout::Error
83
+ # and still attempts its own kill) and log the failure.
84
+ # `slept` guards against a spurious mark if the thread itself
85
+ # dies before the deadline. Thread#kill lands as an
86
+ # uncatchable KillError, so a normal-exit cancellation never
87
+ # reaches this rescue.
88
+ if slept
89
+ deadline_hit = true
90
+ Rubik::Log.warn(:platform, "popen_capture deadline kill failed for pid #{w_pid}: " \
91
+ "#{e.class}: #{e.message}")
92
+ end
93
+ end
74
94
  end
75
95
  begin
76
96
  stdin.close
@@ -114,6 +134,7 @@ module Rubik
114
134
  end
115
135
  raise Timeout::Error, "execution expired" if deadline_hit
116
136
  rescue Timeout::Error
137
+ timed_out = true
117
138
  kill_tree(pid) if pid
118
139
  stderr_str = timeout_message || "Execution timed out after #{timeout} seconds"
119
140
  exit_code = 124
@@ -134,7 +155,11 @@ module Rubik
134
155
  stderr: stderr_str,
135
156
  output: [stdout_str, stderr_str].reject(&:empty?).join("\n"),
136
157
  duration: duration.round(4),
137
- pid: pid
158
+ pid: pid,
159
+ # Explicit timeout flag (issue #597): exit code 124 is also a
160
+ # legitimate exit code of timeout(1) and other workloads, so the
161
+ # tool layer must not re-derive `timed_out` from the exit code.
162
+ timed_out: timed_out || deadline_hit
138
163
  }
139
164
  end
140
165
 
@@ -60,21 +60,23 @@ module Rubik
60
60
  end
61
61
 
62
62
  # PERF: Fast-path deep UTF-8 cleaner. Performs zero-allocation Symbol
63
- # validation via Symbol#name and tracks cycle object IDs in a Hash to
64
- # eliminate Set instance allocations (~3.3x speedup, ~70% faster).
63
+ # validation via Symbol#name and tracks cycle object IDs in a path
64
+ # stack: ids are added on descent and removed after the children are
65
+ # visited, so only objects currently on the traversal path (genuine
66
+ # cycles) are cut — a shared object referenced from two sibling places
67
+ # is emitted in full both times (issue #597).
65
68
  def clean_utf8_deep(obj, seen = nil)
69
+ stack = seen.is_a?(Array) ? seen : []
66
70
  case obj
67
71
  when String
68
72
  clean_utf8(obj)
69
73
  when Symbol
70
74
  fast_clean_symbol(obj)
71
75
  when Hash
72
- seen ||= {}
73
76
  obj_id = obj.object_id
74
- return "{...}" if seen.is_a?(Hash) ? seen.key?(obj_id) : seen.include?(obj_id)
75
-
76
- seen.is_a?(Hash) ? (seen[obj_id] = true) : seen.add(obj_id)
77
+ return "{...}" if stack.include?(obj_id)
77
78
 
79
+ stack << obj_id
78
80
  res = {}
79
81
  obj.each do |k, v|
80
82
  cleaned_k = if k.is_a?(Symbol)
@@ -82,27 +84,24 @@ module Rubik
82
84
  elsif k.is_a?(String)
83
85
  clean_utf8(k)
84
86
  else
85
- clean_utf8_deep(k, seen)
87
+ clean_utf8_deep(k, stack)
86
88
  end
87
- res[cleaned_k] = clean_utf8_deep(v, seen)
89
+ res[cleaned_k] = clean_utf8_deep(v, stack)
88
90
  end
91
+ stack.pop
89
92
  res
90
93
  when Array
91
- seen ||= {}
92
94
  obj_id = obj.object_id
93
- return "[...]" if seen.is_a?(Hash) ? seen.key?(obj_id) : seen.include?(obj_id)
94
-
95
- seen.is_a?(Hash) ? (seen[obj_id] = true) : seen.add(obj_id)
95
+ return "[...]" if stack.include?(obj_id)
96
96
 
97
- obj.map { |item| clean_utf8_deep(item, seen) }
97
+ stack << obj_id
98
+ obj.map { |item| clean_utf8_deep(item, stack) }.tap { stack.pop }
98
99
  when Set
99
- seen ||= {}
100
100
  obj_id = obj.object_id
101
- return Set.new(["[...]"]) if seen.is_a?(Hash) ? seen.key?(obj_id) : seen.include?(obj_id)
102
-
103
- seen.is_a?(Hash) ? (seen[obj_id] = true) : seen.add(obj_id)
101
+ return Set.new(["[...]"]) if stack.include?(obj_id)
104
102
 
105
- obj.to_set { |item| clean_utf8_deep(item, seen) }
103
+ stack << obj_id
104
+ obj.to_set { |item| clean_utf8_deep(item, stack) }.tap { stack.pop }
106
105
  else
107
106
  obj
108
107
  end
@@ -61,6 +61,33 @@ module Rubik
61
61
  env
62
62
  end
63
63
 
64
+ # Credential-shaped variable names stripped from child-process
65
+ # environments (issue #586). Matching is by underscore-delimited
66
+ # segment (case-insensitive) so OPENAI_API_KEY, MY_SECRET and
67
+ # AWS_ACCESS_KEY_ID are covered without matching words like
68
+ # "tokenizer". NOTE: integrity hygiene, NOT a confinement boundary.
69
+ CREDENTIAL_ENV_PATTERN = /
70
+ (?:_|\A)(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|PAT|CREDENTIALS?)(?:_|\z)
71
+ |\A(?:DATABASE|REDIS|MONGO|POSTGRES|MYSQL|AMQP)_URL\z
72
+ |_(?:DATABASE|CONNECTION)_URL\z
73
+ /ix
74
+
75
+ # sanitized_spawn_env plus an explicit nil for every credential-shaped
76
+ # host variable (spawn semantics: nil UNSETs it; benign variables stay
77
+ # out of the hash and remain normally inheritable). Consumers:
78
+ # TaskManager#start (issue #586) and Driver::ProcessDriver#child_env
79
+ # (both now delegate here — single shared CREDENTIAL_ENV_PATTERN).
80
+ # The MCP stdio transport keeps its own narrower pattern on purpose:
81
+ # it matches _REDIS_URL, which this pattern's underscore-URL branch
82
+ # does not, so this pattern is not a safe superset for that path.
83
+ def credential_free_env
84
+ env = sanitized_spawn_env
85
+ ENV.each_key do |key|
86
+ env[key] = nil if key.match?(CREDENTIAL_ENV_PATTERN)
87
+ end
88
+ env
89
+ end
90
+
64
91
  def host_os
65
92
  RbConfig::CONFIG["host_os"] || ""
66
93
  end
@@ -92,6 +92,8 @@ module Rubik
92
92
  # against. Keyed by plugin name (the package root's basename).
93
93
  def record_package(plugin_dir, name, scope: :project)
94
94
  target_dir = scope.to_sym == :global ? global_plugins_dir : project_plugins_dir
95
+ # Fail-closed on a corrupt manifest (issue #596, cf. record_hash).
96
+ manifest_store.refuse_corrupt_manifest!(target_dir, :record, name.to_s)
95
97
  manifest = load_manifest(target_dir)
96
98
  manifest[name.to_s] = {
97
99
  "type" => "directory",
@@ -143,6 +145,9 @@ module Rubik
143
145
 
144
146
  if File.directory?(source_path)
145
147
  plugin_name = File.basename(source_path)
148
+ # Same guard as remove_plugin (issues #554/#596).
149
+ return { ok: false, error: "Invalid plugin name: #{plugin_name.inspect}." } unless safe_plugin_name?(plugin_name, target_dir)
150
+
146
151
  dest_path = File.join(target_dir, plugin_name)
147
152
 
148
153
  if (violation = PackageInventory.violation(source_path))
@@ -159,9 +164,8 @@ module Rubik
159
164
  return { ok: true, name: plugin_name, path: dest_path, type: :directory }
160
165
  end
161
166
 
162
- # Deterministic re-add (also the legacy-manifest re-consent path):
163
- # replace any previous copy so stale helpers cannot survive into
164
- # the newly consented package.
167
+ # Deterministic re-add (also the legacy re-consent path): replace
168
+ # any previous copy so stale helpers cannot survive the re-consent.
165
169
  FileUtils.rm_rf(dest_path)
166
170
  FileUtils.cp_r(source_path, dest_path)
167
171
 
@@ -176,8 +180,12 @@ module Rubik
176
180
 
177
181
  { ok: true, name: plugin_name, path: dest_path, type: :directory }
178
182
  else
183
+ source_name = File.basename(source_path)
179
184
  plugin_name = File.basename(source_path, ".rb")
180
- dest_path = File.join(target_dir, File.basename(source_path))
185
+ # Same guard as remove_plugin (issue #554) before the cp (issue #596).
186
+ return { ok: false, error: "Invalid plugin name: #{plugin_name.inspect}." } unless safe_plugin_name?(source_name, target_dir)
187
+
188
+ dest_path = File.join(target_dir, source_name)
181
189
  FileUtils.cp(source_path, dest_path)
182
190
  record_hash(dest_path, scope: scope)
183
191
 
@@ -224,9 +232,8 @@ module Rubik
224
232
 
225
233
  # A plugin name must resolve to a single path component directly under
226
234
  # target_dir. Reject separators, traversal components (`.`/`..`),
227
- # absolute paths and NUL bytes before any rm_f/rm_rf so a caller-supplied
228
- # name can never escape the plugins directory (issue #554). Any ordinary
229
- # single-component name is allowed, so legitimate plugins keep working.
235
+ # absolute paths and NUL bytes before any rm_f/rm_rf (issue #554).
236
+ # Any ordinary single-component name is allowed, so plugins keep working.
230
237
  def safe_plugin_name?(name, target_dir)
231
238
  component = name.to_s
232
239
  return false if component.empty? || component == "." || component == ".."
@@ -240,8 +247,8 @@ module Rubik
240
247
  end
241
248
 
242
249
  # The package root for a path inside the plugins dir: plugins/<first
243
- # segment> when that segment is a DIRECTORY (directory plugin); nil for
244
- # a single-file plugin. A path outside the plugins dir is not a package.
250
+ # segment> when that segment is a DIRECTORY; nil for a single-file
251
+ # plugin or a path outside the plugins dir.
245
252
  def package_root_for(path, plugins_dir)
246
253
  base = File.expand_path(plugins_dir)
247
254
  prefix = "#{base}#{File::SEPARATOR}"
@@ -259,8 +266,7 @@ module Rubik
259
266
 
260
267
  # Whole-package verification. A legacy (entry-file-only) manifest cannot
261
268
  # vouch for helpers that were never consented to, so it is rejected with
262
- # an explicit re-consent path: re-add the plugin, or opt into trust with
263
- # RUBIK_TRUST_OVERLAYS=1.
269
+ # an explicit re-consent path (re-add, or RUBIK_TRUST_OVERLAYS=1).
264
270
  def verify_package_integrity(package_dir, scope: :project)
265
271
  dir = scope.to_sym == :global ? global_plugins_dir : project_plugins_dir
266
272
  name = File.basename(package_dir)
@@ -201,8 +201,9 @@ module Rubik
201
201
  "dedicated notification-evaluation turn — evaluate the pending notifications, act (extend budget, steer with " \
202
202
  "send_message, retrieve results, wrap up, or report to the user), and conclude your turn again. Subagents can " \
203
203
  "ask YOU questions mid-flight via `ask_question` — a question notification means that subagent is BLOCKED until " \
204
- "you reply: answer it promptly with `send_message(recipient: '<id>', message: '<your answer>')` (it times out " \
205
- "otherwise). Call `#{Rubik::Orchestrator::Subagent::Notices.wait_hint_template}` only when synchronous waiting " \
204
+ "you reply: answer it promptly with `send_message(recipient: '<id>', message: '<your answer>', " \
205
+ "in_reply_to: '<question_id>')` — echo the question_id from the notification, it times out otherwise. " \
206
+ "Call `#{Rubik::Orchestrator::Subagent::Notices.wait_hint_template}` only when synchronous waiting " \
206
207
  "is strictly required. Never poll 'status' repeatedly in a loop."
207
208
  end
208
209
  end
@@ -29,12 +29,16 @@ module Rubik
29
29
 
30
30
  # One honest line for a failed disk write; returns true when it fired
31
31
  # so callers can step past their success report. The in-memory change
32
- # stands — only persistence failed.
32
+ # stands — only persistence failed. `ctx` is the REPL context, but an
33
+ # IO/output stream is also accepted (workspace_approval passes @out
34
+ # directly — issue #598): anything responding to #out is unwrapped,
35
+ # anything else is written to via #puts.
33
36
  def self.report_persist_failure(ctx, res, scope)
34
37
  return false if res.nil? || res[:ok]
35
38
 
36
- ctx.out.puts "Error: could not save to #{scope_label(scope)}: #{res[:error]} " \
37
- "(change kept for this session only)."
39
+ out = ctx.respond_to?(:out) ? ctx.out : ctx
40
+ out.puts "Error: could not save to #{scope_label(scope)}: #{res[:error]} " \
41
+ "(change kept for this session only)."
38
42
  true
39
43
  end
40
44
 
@@ -86,8 +86,12 @@ module Rubik
86
86
  target_path
87
87
  end
88
88
  if ctx.buffer_manager.dirty_files.key?(rel)
89
- full_path = File.expand_path(rel, ctx.buffer_manager.root_dir)
90
- orig_content = File.exist?(full_path) ? File.read(full_path) : ""
89
+ # Route through Manager.read(from_disk: true) so the disk side
90
+ # gets the same read_bytes_as_utf8 encoding as the buffer side
91
+ # (issue #589) — a plain File.read can raise
92
+ # Encoding::CompatibilityError in unified_diff for files with
93
+ # invalid-UTF-8 bytes.
94
+ orig_content = ctx.buffer_manager.read(rel, from_disk: true) || ""
91
95
  new_content = ctx.buffer_manager.read(rel) || ""
92
96
  Rubik::UI::DiffViewer.render(ctx, theme, Rubik::Buffer::Diff.unified_diff(rel, orig_content, new_content))
93
97
  else
@@ -127,6 +127,12 @@ module Rubik
127
127
  FileUtils.mkdir_p(target_dir)
128
128
  target_file = File.join(target_dir, "#{safe_name}.jsonl")
129
129
 
130
+ # Durability barrier before the copy so the copied JSONL can
131
+ # never carry a torn tail from the recorder's append stream
132
+ # (issue #598). Both branches write the same JSONL content; the
133
+ # fallback only fires when no live file exists yet, in which
134
+ # case @events holds the same (recent) events.
135
+ ctx.recorder.flush
130
136
  if ctx.recorder.session_file && File.exist?(ctx.recorder.session_file)
131
137
  FileUtils.cp(ctx.recorder.session_file, target_file)
132
138
  else
@@ -134,7 +140,11 @@ module Rubik
134
140
  ctx.recorder.events.each { |ev| f.puts(JSON.dump(ev)) }
135
141
  end
136
142
  end
137
- ctx.recorder.switch_session_file(target_file, cleanup_empty_current: false)
143
+ # Provenance: the saved copy's parent is the session it was
144
+ # copied FROM (captured before the switch), not the target's
145
+ # own basename (issue #598).
146
+ ctx.recorder.switch_session_file(target_file, cleanup_empty_current: false,
147
+ parent_session_id: ctx.recorder.session_id)
138
148
  ctx.out.puts "[Rubik::Session] Session saved to #{target_file}"
139
149
  end
140
150
 
@@ -212,7 +212,7 @@ module Rubik
212
212
  # context already includes the idle-injected notices. The notice
213
213
  # turn itself drains first, so this clear is a no-op for it.
214
214
  clear_pending_wake_notices! if respond_to?(:clear_pending_wake_notices!)
215
- @recorder&.record_user_turn(text)
215
+ @recorder&.record_user_turn(text) unless @replaying
216
216
  @event_bus.emit(:prompt_received, prompt: text)
217
217
  task
218
218
  end
@@ -270,12 +270,12 @@ module Rubik
270
270
  md_stream.finish { |seg| @output.print seg }
271
271
  @output.flush if @output.respond_to?(:flush)
272
272
  when :tool_call
273
- @recorder&.record_tool_call(step_info[:tool], step_info[:args], call_id: step_info[:call_id])
273
+ @recorder&.record_tool_call(step_info[:tool], step_info[:args], call_id: step_info[:call_id]) unless @replaying
274
274
  formatted = renderer.render(step_info)
275
275
  @output.puts formatted if formatted && !formatted.empty?
276
276
  @output.flush if @output.respond_to?(:flush)
277
277
  when :tool_result
278
- @recorder&.record_tool_result(step_info[:tool], step_info[:output], status: step_info[:status] || :ok, call_id: step_info[:call_id])
278
+ @recorder&.record_tool_result(step_info[:tool], step_info[:output], status: step_info[:status] || :ok, call_id: step_info[:call_id]) unless @replaying
279
279
  formatted = renderer.render(step_info)
280
280
  @output.puts formatted if formatted && !formatted.empty?
281
281
  @output.flush if @output.respond_to?(:flush)
@@ -138,8 +138,12 @@ module Rubik
138
138
  DEFINITION.new(
139
139
  name: :snapshot_store,
140
140
  builder: lambda do |s|
141
- Rubik::Buffer::SnapshotStore.new(storage_dir: File.join(s.home_dir, ".rubik", "snapshots",
142
- File.basename(s.root_dir)))
141
+ # Issue #589: debounced snapshot persistence (undo granularity
142
+ # stays in memory) + on-disk retention cap.
143
+ Rubik::Buffer::SnapshotStore.new(
144
+ storage_dir: File.join(s.home_dir, ".rubik", "snapshots", File.basename(s.root_dir)),
145
+ min_interval: 1.0, max_snapshots: 200
146
+ )
143
147
  end,
144
148
  provide: Rubik::Coeffects::SNAPSHOT_STORE
145
149
  ),
@@ -47,7 +47,10 @@ module Rubik
47
47
  @conversation_history << { role: "user", content: user_text }
48
48
  @conversation_history << { role: "assistant", content: assistant_content.to_s }
49
49
  trim_conversation_window!
50
- @recorder&.record_assistant_response(assistant_content.to_s, tokens: tokens, streamed: streamed)
50
+ # Same one policy as the input record (shell.rb): replayed turns
51
+ # hydrate the conversation window but must not re-record events
52
+ # into the active session JSONL (issue #598).
53
+ @recorder&.record_assistant_response(assistant_content.to_s, tokens: tokens, streamed: streamed) unless @replaying
51
54
  rescue StandardError => e
52
55
  Rubik::Platform.debug_warn("turn outcome recording failed (#{e.class}: #{e.message}); turn lost from conversation memory")
53
56
  nil
@@ -59,8 +59,11 @@ module Rubik
59
59
 
60
60
  # Per-basename hash record: load → merge → save. The caller owns hash
61
61
  # computation (file vs normalized content) and pre-write guards; the
62
- # store owns the entry shape and the manifest mutation.
62
+ # store owns the entry shape and the manifest mutation. Fail-closed on
63
+ # a corrupt manifest — recording would rewrite it with only the new
64
+ # entry and evict the other consented records (issue #596).
63
65
  def record_hash(dir, filename, hash, scope:)
66
+ refuse_corrupt_manifest!(dir, :record, filename)
64
67
  manifest = load_manifest(dir)
65
68
  manifest[filename] = {
66
69
  "sha256" => hash,
@@ -71,8 +74,10 @@ module Rubik
71
74
  end
72
75
 
73
76
  # Symmetric retraction: remove a basename and persist. Returns whether
74
- # the key existed (mirrors Hash#delete's semantics).
77
+ # the key existed (mirrors Hash#delete's semantics). Fail-closed on a
78
+ # corrupt manifest for the same eviction reason as record_hash.
75
79
  def remove_entry(dir, filename)
80
+ refuse_corrupt_manifest!(dir, :delete, filename)
76
81
  manifest = load_manifest(dir)
77
82
  existed = manifest.delete(filename)
78
83
  save_manifest(dir, manifest) if existed
@@ -6,12 +6,14 @@ require "time"
6
6
  require_relative "../log"
7
7
  require_relative "../platform"
8
8
  require_relative "../security/guard" unless defined?(Rubik::Security::Guard)
9
+ require_relative "../security/redactor" unless defined?(Rubik::Security::Redactor)
9
10
 
10
11
  module Rubik
11
12
  module Runtime
12
- # Bounded thread-safe ring buffer for capturing child process stdout/stderr
13
- # without risk of unbounded memory growth (Plan 93).
13
+ # Bounded ring buffer for child stdout/stderr (Plan 93): bounded by entry
14
+ # count AND per-line bytes; lines are Redactor-redacted at push time (#586).
14
15
  class RingBuffer
16
+ MAX_LINE_BYTES = 64 * 1024 # byte cap per line (scrub re-validates cut chars)
15
17
  attr_reader :capacity
16
18
 
17
19
  def initialize(capacity = 500)
@@ -21,8 +23,11 @@ module Rubik
21
23
  end
22
24
 
23
25
  def push(line)
26
+ text = line.to_s
27
+ text = text.byteslice(0, MAX_LINE_BYTES).scrub if text.bytesize > MAX_LINE_BYTES
28
+ clean = Rubik::Security::Redactor.redact(text)
24
29
  @monitor.synchronize do
25
- @buffer << line.to_s
30
+ @buffer << clean
26
31
  @buffer.shift while @buffer.size > @capacity
27
32
  end
28
33
  self
@@ -76,9 +81,8 @@ module Rubik
76
81
  end
77
82
  end
78
83
 
79
- # Manages asynchronous long-running background processes (servers, builders,
80
- # watchers) with deadlock-immune streaming, AST guard verification, and
81
- # context-mediated LIFO rollback (AGENTS.md §1.A/B, Plan 93).
84
+ # Manages asynchronous long-running background processes with
85
+ # deadlock-immune streaming, AST guard verification and LIFO rollback.
82
86
  class TaskManager
83
87
  attr_reader :guard, :context, :root_dir, :max_buffer_lines
84
88
  attr_accessor :init
@@ -151,11 +155,10 @@ module Rubik
151
155
  # #444): that core is the synchronous drain-to-string capture shape
152
156
  # (Timeout-wrapped, stdin closed immediately, whole-output strings).
153
157
  # This spawn is the async/interactive shape — stdin stays open for
154
- # send_input, the readers stream chomped lines into the per-task
155
- # RingBuffer, and completion is watched by a dedicated thread with
156
- # no Timeout — so parameterizing the sink alone cannot unify them.
158
+ # send_input, readers stream chomped lines into the per-task
159
+ # RingBuffer, completion is watched by a dedicated thread.
157
160
  begin
158
- stdin, stdout, stderr, wait_thr = Open3.popen3(cmd_str, chdir: chdir)
161
+ stdin, stdout, stderr, wait_thr = Open3.popen3(Rubik::Platform.credential_free_env, cmd_str, chdir: chdir)
159
162
  rescue StandardError => e
160
163
  rollback_failed_start(target_ctx, nil, e)
161
164
  raise e
@@ -1,5 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "../../security/guard" unless defined?(Rubik::Security::Guard)
4
+
3
5
  module Rubik
4
6
  module Sandbox
5
7
  module Driver
@@ -31,6 +33,38 @@ module Rubik
31
33
  def run(cmd, timeout: 15, chdir: Dir.pwd, allow_network: false, memory_limit_mb: 512, cpus: "1.0")
32
34
  raise NotImplementedError
33
35
  end
36
+
37
+ private
38
+
39
+ # Security guard gating spawns (issue #591). The Runner injects the
40
+ # shared session guard via driver_opts (options[:guard]) so operator
41
+ # policy — the live command allowlist above all — applies to every
42
+ # driver; the lazy local fallback (silent audit, zero policy) serves
43
+ # only standalone / test-constructed drivers. ProcessDriver keeps its
44
+ # own copy with cmd.exe refinements; container drivers re-verify the
45
+ # raw command through this shared helper before spawning.
46
+ def guard
47
+ @options[:guard] || (@guard ||= Rubik::Security::Guard.new(audit_log_path: nil))
48
+ end
49
+
50
+ # Re-run the security guard's classification before spawning. Blocks
51
+ # a command the operator policy / catastrophic fallback regex rejects.
52
+ def verify_command_safety!(cmd, shell: nil)
53
+ guard.verify_command_safety!(cmd, shell: shell)
54
+ true
55
+ end
56
+
57
+ # Issue #591: bind-mount every configured allowed dir read-write,
58
+ # mirroring BubblewrapDriver's loop, so commands legitimately touching
59
+ # an allowed external dir work identically across drivers.
60
+ def allowed_dir_mounts
61
+ Array(@options[:allowed_dirs]).filter_map do |dir|
62
+ expanded = File.expand_path(dir.to_s)
63
+ next unless File.directory?(expanded)
64
+
65
+ ["-v", "#{expanded}:#{expanded}:rw"]
66
+ end.flatten
67
+ end
34
68
  end
35
69
  end
36
70
  end
@@ -75,6 +75,8 @@ module Rubik
75
75
  {
76
76
  ok: res[:ok],
77
77
  exit_code: res[:exit_code],
78
+ # Explicit timeout flag plumbed to the tool layer (#597-3).
79
+ timed_out: res[:timed_out] == true,
78
80
  stdout: res[:stdout],
79
81
  stderr: res[:stderr],
80
82
  output: res[:output],
@@ -19,6 +19,11 @@ module Rubik
19
19
  end
20
20
 
21
21
  def run(cmd, timeout: 15, chdir: Dir.pwd, allow_network: false, memory_limit_mb: 512, cpus: "1.0")
22
+ # Defense-in-depth (issue #591): re-run the shared session guard
23
+ # before spawning, the same way ProcessDriver does, so a caller
24
+ # that forgot its own pre-check is still gated by operator policy.
25
+ verify_command_safety!(cmd)
26
+
22
27
  image = @options[:image] || DEFAULT_IMAGE
23
28
  workspace = File.expand_path(chdir)
24
29
  container_name = "rubik-box-#{SecureRandom.hex(6)}"
@@ -29,6 +34,7 @@ module Rubik
29
34
  *CONTAINER_HARDENING_FLAGS,
30
35
  "-w", "/workspace",
31
36
  "-v", "#{workspace}:/workspace:rw",
37
+ *allowed_dir_mounts,
32
38
  "--memory", "#{memory_limit_mb}m",
33
39
  "--cpus", cpus.to_s,
34
40
  "--pids-limit", "100"
@@ -55,6 +61,8 @@ module Rubik
55
61
  {
56
62
  ok: res[:ok],
57
63
  exit_code: res[:exit_code],
64
+ # Explicit timeout flag plumbed to the tool layer (#597-3).
65
+ timed_out: res[:timed_out] == true,
58
66
  stdout: res[:stdout],
59
67
  stderr: res[:stderr],
60
68
  output: res[:output],
@@ -16,6 +16,11 @@ module Rubik
16
16
  end
17
17
 
18
18
  def run(cmd, timeout: 15, chdir: Dir.pwd, allow_network: false, memory_limit_mb: 512, cpus: "1.0")
19
+ # Defense-in-depth (issue #591): re-run the shared session guard
20
+ # before spawning, the same way ProcessDriver does, so a caller
21
+ # that forgot its own pre-check is still gated by operator policy.
22
+ verify_command_safety!(cmd)
23
+
19
24
  image = @options[:image] || DEFAULT_IMAGE
20
25
  workspace = File.expand_path(chdir)
21
26
 
@@ -24,6 +29,7 @@ module Rubik
24
29
  *CONTAINER_HARDENING_FLAGS,
25
30
  "-w", "/workspace",
26
31
  "-v", "#{workspace}:/workspace:rw",
32
+ *allowed_dir_mounts,
27
33
  "--memory", "#{memory_limit_mb}m",
28
34
  "--cpus", cpus.to_s,
29
35
  "--pids-limit", "100"
@@ -43,6 +49,8 @@ module Rubik
43
49
  {
44
50
  ok: res[:ok],
45
51
  exit_code: res[:exit_code],
52
+ # Explicit timeout flag plumbed to the tool layer (#597-3).
53
+ timed_out: res[:timed_out] == true,
46
54
  stdout: res[:stdout],
47
55
  stderr: res[:stderr],
48
56
  output: res[:output],
@@ -19,12 +19,9 @@ module Rubik
19
19
  # AWS_ACCESS_KEY_ID are covered without matching words like "tokenizer".
20
20
  # NOTE: this is integrity hygiene, NOT a secret-confinement boundary —
21
21
  # the child still inherits non-credential host variables by design.
22
- CREDENTIAL_ENV_PATTERN = /
23
- (?:_|\A)(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|PAT|CREDENTIALS?)(?:_|\z)
24
- |\A(?:DATABASE|REDIS|MONGO|POSTGRES|MYSQL|AMQP)_URL\z
25
- |_(?:DATABASE|CONNECTION)_URL\z
26
- /ix
27
- private_constant :CREDENTIAL_ENV_PATTERN
22
+ # The credential pattern and the env construction live once in
23
+ # Rubik::Platform.credential_free_env (issue #586); this driver is a
24
+ # pure consumer of that shared implementation.
28
25
 
29
26
  def available?
30
27
  true
@@ -49,6 +46,9 @@ module Rubik
49
46
  {
50
47
  ok: res[:ok],
51
48
  exit_code: res[:exit_code],
49
+ # Explicit timeout flag plumbed to the tool layer (#597-3): a
50
+ # legitimate timeout(1) exit 124 must not read as a runner kill.
51
+ timed_out: res[:timed_out] == true,
52
52
  stdout: clean_stdout,
53
53
  stderr: clean_stderr,
54
54
  output: [clean_stdout, clean_stderr].reject(&:empty?).join("\n"),
@@ -66,13 +66,10 @@ module Rubik
66
66
  # child cannot observe or dump them. Benign variables are left out of
67
67
  # the hash entirely and therefore remain normally inheritable, which
68
68
  # keeps legitimate command execution (PATH, HOME, locale, proxies…)
69
- # working. See CREDENTIAL_ENV_PATTERN for the shape that is stripped.
69
+ # working. See Rubik::Platform::CREDENTIAL_ENV_PATTERN for the shape
70
+ # that is stripped.
70
71
  def child_env
71
- env = Rubik::Platform.sanitized_spawn_env
72
- ENV.each_key do |key|
73
- env[key] = nil if key.match?(CREDENTIAL_ENV_PATTERN)
74
- end
75
- env
72
+ Rubik::Platform.credential_free_env
76
73
  end
77
74
 
78
75
  # cmd.exe parses its tail with its own quoting rules that standard