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
@@ -29,6 +29,14 @@ module Rubik
29
29
 
30
30
  def run(cmd, timeout: 15, chdir: Dir.pwd, allow_network: false, memory_limit_mb: 512, cpus: "1.0") # rubocop:disable Lint/UnusedMethodArgument -- sürücü arayüzü kwarg'leri korunuyor
31
31
  resolved = ShellResolver.resolve(cmd, preference: @options[:shell] || "auto")
32
+ # Defense in depth: the POSIX argv path used to reach spawn with no
33
+ # gate at all (only the cmd.exe branch re-verified). Gate it here.
34
+ # cmd is already gated inside verify_cmd_safe with cmd semantics.
35
+ # PowerShell cmdlets use a different vocabulary the POSIX classifier
36
+ # cannot classify. pwsh routing therefore relies on the upstream
37
+ # RunCommandTool gate; direct Sandbox::Runner callers must gate first.
38
+ # A PowerShell-aware classifier is tracked as a follow-up.
39
+ verify_command_safety!(cmd) unless ["cmd", "pwsh"].include?(resolved[:shell])
32
40
  env = child_env
33
41
 
34
42
  res = Rubik::Platform.popen_capture(
@@ -39,23 +47,12 @@ module Rubik
39
47
  )
40
48
 
41
49
  stderr_out = resolved[:note] ? "#{resolved[:note]}\n#{res[:stderr]}" : res[:stderr]
42
- require_relative "../../security/redactor" unless defined?(Rubik::Security::Redactor)
43
- clean_stdout = Rubik::Security::Redactor.redact(res[:stdout])
44
- clean_stderr = Rubik::Security::Redactor.redact(stderr_out)
45
50
 
46
- {
47
- ok: res[:ok],
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
- stdout: clean_stdout,
53
- stderr: clean_stderr,
54
- output: [clean_stdout, clean_stderr].reject(&:empty?).join("\n"),
55
- duration: res[:duration],
56
- driver: "process",
57
- shell: resolved[:shell]
58
- }
51
+ finalize_result(
52
+ res,
53
+ stderr: stderr_out,
54
+ extra: { shell: resolved[:shell] }
55
+ )
59
56
  end
60
57
 
61
58
  private
@@ -133,30 +130,14 @@ module Rubik
133
130
  raise_dangerous(cmd.to_s, rule_name: "cmd.exe_construct")
134
131
  end
135
132
 
136
- # Security guard gating cmd.exe spawns. The Runner injects the shared
137
- # session guard via driver_opts (options[:guard]) so operator policy —
138
- # the live command allowlist above all — applies here too; the lazy
139
- # local fallback (silent audit, zero policy) serves only standalone /
140
- # test-constructed drivers.
141
- def guard
142
- @options[:guard] || (@guard ||= Rubik::Security::Guard.new(audit_log_path: nil))
143
- end
144
-
145
- # Re-run the security guard's classification, scoped to the given shell
146
- # so cmd.exe semantics are enforced when spawned via cmd. Blocks a
147
- # POSIX-safe-but-cmd-dangerous command with BlockedWriteError.
148
- def verify_command_safety!(cmd, shell: nil)
149
- guard.verify_command_safety!(cmd, shell: shell)
150
- true
151
- end
152
-
153
133
  # Raise the standard BlockedWriteError used throughout the guard
154
134
  # surface for an explicitly detected dangerous construct.
155
135
  def raise_dangerous(cmd, rule_name:)
136
+ display = Rubik::Security.display_command(cmd)
156
137
  raise Rubik::Security::BlockedWriteError.new(
157
- "Dangerous command execution blocked: #{cmd}",
138
+ "Dangerous command execution blocked: #{display}",
158
139
  kind: :cmd_construct,
159
- blocked_command: cmd,
140
+ blocked_command: display,
160
141
  rule_name: rule_name
161
142
  )
162
143
  end
@@ -24,12 +24,14 @@ module Rubik
24
24
  # one-liner: `!allow-cmd add "<command>"`.
25
25
  def self.render(err)
26
26
  cmd = err.respond_to?(:blocked_command) ? err.blocked_command : nil
27
+ cmd = Rubik::Security.display_command(cmd) if cmd
27
28
  rule = err.respond_to?(:rule_name) ? err.rule_name : nil
28
29
  kind = err.respond_to?(:kind) ? err.kind : nil
29
30
  quoted = cmd ? "\"#{cmd}\"" : nil
30
31
  # Unstructured raises (critical-write) carry all their context in
31
- # #message — never discard it behind "rule: unknown".
32
- message = err.message
32
+ # #message — never discard it behind "rule: unknown". Defense in depth:
33
+ # escape control chars even if a raise site forgets to.
34
+ message = Rubik::Security.display_command(err.message)
33
35
  structural = cmd || rule
34
36
 
35
37
  lines = if kind == :chdir_outside_root
@@ -63,6 +63,8 @@ module Rubik
63
63
  # whose ONLY arguments are these flags is read-only by construction.
64
64
  SAFE_PROBE_FLAGS = ["--version", "-v", "--help", "-h"].freeze
65
65
 
66
+ SHELL_METACHAR_PATTERN = /[;&|`$<>(){}\n\r]/
67
+
66
68
  attr_accessor :shell, :root_dir
67
69
 
68
70
  def initialize(allowlist:, audit:, path_policy:, allow_safe_probes: true,
@@ -123,6 +125,11 @@ module Rubik
123
125
  def probe_shape?(cmd_str)
124
126
  str = cmd_str.to_s
125
127
  return false if str.match?(/[\r\n]/)
128
+ # ShellResolver passes the raw string to `sh -c`/`bash -c`, while this
129
+ # detector tokenizes with Shellwords. Exact-flag allowlisting already
130
+ # excludes metacharacters; keep the explicit check so a future flag
131
+ # addition cannot reopen the gap.
132
+ return false if str.match?(SHELL_METACHAR_PATTERN)
126
133
 
127
134
  tokens = shell_tokens(str)
128
135
  return false unless tokens
@@ -216,11 +223,11 @@ module Rubik
216
223
  # today) keeps flowing into its own deny layers
217
224
  # (DANGEROUS_SYNTHESIS_PATTERNS + RubyVM walk) after this gate.
218
225
  if allow_unknown
219
- Rubik::Log.warn(:security, "[WARN] AST classification error on non-shell input, continuing to synthesis deny layers: #{e.message}")
226
+ Rubik::Log.warn(:security, "[WARN] AST classification error on non-shell input, continuing to synthesis deny layers: #{display_command(e.message)}")
220
227
  @audit.log_audit("classifier_error", command: cmd_str, reason: "#{e.class}: #{e.message}",
221
228
  decision: "synthesis_layers")
222
229
  else
223
- Rubik::Log.warn(:security, "[WARN] AST classification error, failing closed: #{e.class}: #{e.message}")
230
+ Rubik::Log.warn(:security, "[WARN] AST classification error, failing closed: #{e.class}: #{display_command(e.message)}")
224
231
  block_on_classifier_failure!(cmd_str, e)
225
232
  end
226
233
  end
@@ -233,15 +240,21 @@ module Rubik
233
240
 
234
241
  @audit.log_audit("blocked_command", command: cmd_str, reason: "dangerous_pattern")
235
242
  raise BlockedWriteError.new(
236
- "Dangerous command execution blocked: #{cmd_str}",
243
+ "Dangerous command execution blocked: #{display_command(cmd_str)}",
237
244
  kind: :dangerous_pattern,
238
- blocked_command: cmd_str,
245
+ blocked_command: display_command(cmd_str),
239
246
  rule_name: "dangerous_pattern"
240
247
  )
241
248
  end
242
249
 
243
250
  private
244
251
 
252
+ # Human-facing rendering only; the shared helper keeps every block-error
253
+ # raise site consistent. Raw bytes still drive execution and the audit.
254
+ def display_command(value)
255
+ Rubik::Security.display_command(value)
256
+ end
257
+
245
258
  # Shellword tokenization for probe-shape detection; nil when the string
246
259
  # has none (unbalanced quotes). The caller fails closed on nil rather
247
260
  # than guessing with whitespace splitting — a quote-corrupted command
@@ -304,7 +317,7 @@ module Rubik
304
317
  def dangerous_segment_report_or_nil(commands)
305
318
  SegmentReport.build(commands)
306
319
  rescue StandardError => e
307
- Rubik::Log.warn(:security, "[Guard] segment report failed: #{e.class}: #{e.message}")
320
+ Rubik::Log.warn(:security, "[Guard] segment report failed: #{e.class}: #{display_command(e.message)}")
308
321
  nil
309
322
  end
310
323
 
@@ -318,9 +331,9 @@ module Rubik
318
331
  # the exemption is disabled, so safe_probe? would be constantly
319
332
  # false and the variant-(a) probe guidance would be dead code.
320
333
  raise BlockedWriteError.new(
321
- "Dangerous command execution blocked: #{cmd_str} (reason: #{reason})",
334
+ "Dangerous command execution blocked: #{display_command(cmd_str)} (reason: #{reason})",
322
335
  kind: :dangerous_command,
323
- blocked_command: cmd_str,
336
+ blocked_command: display_command(cmd_str),
324
337
  rule_name: dangerous_rule_name(ast.commands) || (expression_reason ? "expression_level" : "dangerous_pattern"),
325
338
  probe_like: probe_shape?(cmd_str),
326
339
  segment_report: report,
@@ -341,7 +354,7 @@ module Rubik
341
354
  theme = (effective_shell.respond_to?(:ui_theme) && effective_shell.ui_theme) ||
342
355
  (defined?(Rubik::UI::Theme) ? Rubik::UI::Theme.new : nil)
343
356
 
344
- question = "Allow unclassified command execution: '#{cmd_str}'?"
357
+ question = "Allow unclassified command execution: '#{display_command(cmd_str)}'?"
345
358
  answer = if defined?(Rubik::UI::Approvals)
346
359
  Rubik::UI::Approvals.keypress_yes_no(effective_shell, question, theme: theme, default: "n")
347
360
  else
@@ -357,11 +370,11 @@ module Rubik
357
370
  def block_unknown_command!(cmd_str)
358
371
  @audit.log_audit("blocked_command", command: cmd_str, reason: "unknown_command")
359
372
  raise BlockedWriteError.new(
360
- "Unknown command execution blocked (fail-closed): #{cmd_str}. The binary is not in the " \
373
+ "Unknown command execution blocked (fail-closed): #{display_command(cmd_str)}. The binary is not in the " \
361
374
  "command database, so its effects cannot be classified. If it is genuinely safe, the " \
362
375
  "operator can allowlist the exact prefix: !allow-cmd add \"<binary> [args]\"",
363
376
  kind: :unknown_command,
364
- blocked_command: cmd_str,
377
+ blocked_command: display_command(cmd_str),
365
378
  rule_name: "unknown_command",
366
379
  probe_like: probe_shape?(cmd_str),
367
380
  segment_report: nil
@@ -372,9 +385,9 @@ module Rubik
372
385
  @audit.log_audit("blocked_command", command: cmd_str, reason: "parse_ambiguous",
373
386
  parse_warnings: ast.parse_warnings.to_a.size)
374
387
  raise BlockedWriteError.new(
375
- "Command AST could not be fully parsed (tree-sitter syntax error); execution blocked (fail-closed): #{cmd_str}",
388
+ "Command AST could not be fully parsed (tree-sitter syntax error); execution blocked (fail-closed): #{display_command(cmd_str)}",
376
389
  kind: :parse_ambiguous,
377
- blocked_command: cmd_str,
390
+ blocked_command: display_command(cmd_str),
378
391
  rule_name: "parse_ambiguous",
379
392
  probe_like: probe_shape?(cmd_str),
380
393
  segment_report: nil
@@ -444,9 +457,9 @@ module Rubik
444
457
  verify_command_fallback_regex!(cmd_str)
445
458
  @audit.log_audit("blocked_command", command: cmd_str, reason: "classifier_error")
446
459
  raise BlockedWriteError.new(
447
- "AST evaluation failed, so the command could not be classified; execution blocked (fail-closed): #{cmd_str}",
460
+ "AST evaluation failed, so the command could not be classified; execution blocked (fail-closed): #{display_command(cmd_str)}",
448
461
  kind: :classifier_error,
449
- blocked_command: cmd_str,
462
+ blocked_command: display_command(cmd_str),
450
463
  rule_name: "classifier_error",
451
464
  probe_like: probe_shape?(cmd_str),
452
465
  segment_report: nil
@@ -2,6 +2,19 @@
2
2
 
3
3
  module Rubik
4
4
  module Security
5
+ CONTROL_ESCAPES = { "\n" => "\\n", "\r" => "\\r", "\t" => "\\t", "\0" => "\\0", "\e" => "\\e" }.freeze
6
+ CONTROL_CHAR_PATTERN = /[\x00-\x1F\x7F\u0080-\u009F]/
7
+
8
+ # Escape control characters before command text reaches human- or
9
+ # model-facing output (errors, warnings, approval prompts). Raw bytes still
10
+ # drive classification, execution and the JSONL audit record. Shared so
11
+ # every BlockedWriteError raise site renders identically (#638).
12
+ def self.display_command(value)
13
+ value.to_s.scrub.gsub(CONTROL_CHAR_PATTERN) do |ch|
14
+ CONTROL_ESCAPES.fetch(ch) { format("\\x%02X", ch.ord) }
15
+ end
16
+ end
17
+
5
18
  # Carries structured context (command, rule name, probe-ness, block kind,
6
19
  # offending path) so callers can render situation-specific guidance
7
20
  # instead of regex-munging #message. Kept in its own file: consumers that
@@ -174,8 +174,17 @@ module Rubik
174
174
  @command_gate.allow_safe_probes = val
175
175
  end
176
176
 
177
- def verify_command_safety!(cmd, shell: nil, allow_unknown: false)
178
- @command_gate.verify_command_safety!(cmd, shell: shell, allow_unknown: allow_unknown)
177
+ def verify_command_safety!(cmd, shell: nil)
178
+ @command_gate.verify_command_safety!(cmd, shell: shell)
179
+ end
180
+
181
+ # Restricted seam for non-shell source (synthesis): the permissive
182
+ # allow_unknown path is NOT reachable from the general shell gate, so a
183
+ # future caller cannot accidentally let an unclassified binary through
184
+ # by forwarding an option. Synthesis keeps its own regex + RubyVM deny
185
+ # layers; this gate only supplies classifier-crash diagnostics.
186
+ def verify_synthesis_source!(source)
187
+ @command_gate.verify_command_safety!(source, allow_unknown: true)
179
188
  end
180
189
 
181
190
  def verify_command_fallback_regex!(cmd_str)
@@ -103,10 +103,11 @@ module Rubik
103
103
  write_targets.uniq.each do |wp|
104
104
  if critical_path?(wp)
105
105
  @audit.log_audit("blocked_command", command: cmd_str, reason: "critical_path_write", path: wp)
106
+ display = Rubik::Security.display_command(cmd_str)
106
107
  raise BlockedWriteError.new(
107
- "Command write to critical path blocked: #{wp} in `#{cmd_str}`",
108
+ "Command write to critical path blocked: #{wp} in `#{display}`",
108
109
  kind: :critical_path_write,
109
- blocked_command: cmd_str,
110
+ blocked_command: display,
110
111
  path: wp
111
112
  )
112
113
  end
@@ -119,20 +120,22 @@ module Rubik
119
120
  resolved = Rubik::Platform.resolved_path(wp, strict: true)
120
121
  if resolved.nil?
121
122
  @audit.log_audit("blocked_command", command: cmd_str, reason: "path_resolution_failed", path: wp)
123
+ display = Rubik::Security.display_command(cmd_str)
122
124
  raise BlockedWriteError.new(
123
- "Command write blocked: path could not be safely resolved: #{wp} in `#{cmd_str}`",
125
+ "Command write blocked: path could not be safely resolved: #{wp} in `#{display}`",
124
126
  kind: :critical_path_write,
125
- blocked_command: cmd_str,
127
+ blocked_command: display,
126
128
  path: wp
127
129
  )
128
130
  end
129
131
  next unless critical_path?(resolved)
130
132
 
131
133
  @audit.log_audit("blocked_command", command: cmd_str, reason: "critical_path_write_symlink", path: wp, resolved: resolved)
134
+ display = Rubik::Security.display_command(cmd_str)
132
135
  raise BlockedWriteError.new(
133
- "Command write to critical path blocked (symlink-resolved): #{wp} -> #{resolved} in `#{cmd_str}`",
136
+ "Command write to critical path blocked (symlink-resolved): #{wp} -> #{resolved} in `#{display}`",
134
137
  kind: :critical_path_write,
135
- blocked_command: cmd_str,
138
+ blocked_command: display,
136
139
  path: wp
137
140
  )
138
141
  end
@@ -24,8 +24,9 @@ module Rubik
24
24
  # fiziki => <root>/<project>/store/{meta.json,<type>.jsonl}
25
25
  # indeks => <root>/index.json (merkezi; proje sayıları + zaman damgaları)
26
26
  #
27
- # Tek kullanıcı CLI ölçeği: süreç içi Monitor ile thread-güvenli; çapraz
28
- # süreç yazımlarında meta/index last-writer-wins (belgelenmiş sınırlama).
27
+ # Tek kullanıcı CLI ölçeği: süreç içi Monitor ile thread-güvenli; index.json
28
+ # çapraz süreç yazımlarında flock ile serileştirilir, meta.json ise
29
+ # last-writer-wins (belgelenmiş sınırlama).
29
30
  # Yazmalar Platform.atomic_write ile tmp+rename; kurulum tembeldir —
30
31
  # ilk mutasyona kadar hiçbir dizin oluşturulmaz (standalone/test
31
32
  # kurulumu dosya sistemine dokunmaz).
@@ -34,6 +35,9 @@ module Rubik
34
35
  ID_PATTERN = /\A([a-z]+)\.(\d+)\.([0-9a-f]{16})\z/
35
36
  HASH_PREFIX_MIN = 8
36
37
  REF_PATTERN = /\A[a-zA-Z0-9._-]+\z/
38
+ # File::NOFOLLOW is POSIX-only; on Windows the advisory-flock guard
39
+ # remains and only the symlink refusal is unavailable.
40
+ LOCK_NOFOLLOW = defined?(File::NOFOLLOW) ? File::NOFOLLOW : 0
37
41
 
38
42
  Summary = Struct.new(:id, :row, :title, :status, :updated_at, :tags, keyword_init: true)
39
43
 
@@ -467,16 +471,32 @@ module Rubik
467
471
 
468
472
  # Merkezi indeksi günceller: bu projenin girdisi canlı meta'dan
469
473
  # yeniden yazılır, diğer projelerin girdileri korunur.
474
+ # @monitor yalnızca TEK Store örneğini serileştirir; farkı projelerin
475
+ # Store'ları (ve ayrı süreçler) aynı indeksi hedefleyebilir. Okuma-değiştirme-
476
+ # yazımı indeksten türetilen sabit bir kilit dosyasında flock ile seri
477
+ # hale getiririz; kilit yalnızca bu kısa kritik bölümü kapsar.
470
478
  def touch_index(meta)
471
- snapshot = self.class.index_snapshot(@root)
472
- snapshot["projects"][@project] = {
473
- "path" => project_dir,
474
- "entity_counts" => meta.fetch("counts", {}).dup,
475
- "created_at" => (snapshot["projects"][@project] || {})["created_at"] || meta["created_at"],
476
- "updated_at" => meta["updated_at"]
477
- }
478
- snapshot["updated_at"] = meta["updated_at"]
479
- Rubik::Platform.atomic_write(Layout.index_path(@root), JSON.pretty_generate(snapshot))
479
+ path = Layout.index_path(@root)
480
+ lock_path = "#{path}.lock"
481
+ FileUtils.mkdir_p(File.dirname(lock_path))
482
+ # NOFOLLOW+0600: a pre-placed symlink at the derived lock path must not
483
+ # redirect the flock to an arbitrary file in a shared storage root.
484
+ File.open(lock_path, File::RDWR | File::CREAT | LOCK_NOFOLLOW, 0o600) do |lock|
485
+ lock.flock(File::LOCK_EX)
486
+ begin
487
+ snapshot = self.class.index_snapshot(@root)
488
+ snapshot["projects"][@project] = {
489
+ "path" => project_dir,
490
+ "entity_counts" => meta.fetch("counts", {}).dup,
491
+ "created_at" => (snapshot["projects"][@project] || {})["created_at"] || meta["created_at"],
492
+ "updated_at" => meta["updated_at"]
493
+ }
494
+ snapshot["updated_at"] = meta["updated_at"]
495
+ Rubik::Platform.atomic_write(path, JSON.pretty_generate(snapshot))
496
+ ensure
497
+ lock.flock(File::LOCK_UN)
498
+ end
499
+ end
480
500
  end
481
501
  end
482
502
  end
@@ -3,6 +3,7 @@
3
3
  require "stringio"
4
4
  require_relative "../base"
5
5
  require_relative "../output"
6
+ require_relative "../symbol_tool_support"
6
7
  require_relative "../../security/blocked_guidance"
7
8
 
8
9
  module Rubik
@@ -149,7 +150,10 @@ module Rubik
149
150
 
150
151
  def execute(args = {})
151
152
  cmd = (args["command"] || args[:command]).to_s.strip
152
- background = args["background"] || args[:background]
153
+ return ToolOutput.error("Error: `command` parameter is required and must not be empty.") if cmd.empty?
154
+
155
+ background, flag_error = SymbolToolSupport.boolean_argument(args, "background")
156
+ return flag_error if flag_error
153
157
  return execute_background(cmd) if background
154
158
 
155
159
  timeout = effective_timeout(args)
@@ -111,6 +111,8 @@ module Rubik
111
111
  return ToolOutput.error("Error: Invalid file path '#{path}'. Path must be a valid file path " \
112
112
  "relative to the project root (e.g. 'lib/app.rb', 'src/main.go', 'Gemfile').")
113
113
  end
114
+ shape_ok = Rubik::Buffer::PathValidator.contained_relative?(path)
115
+ return ToolOutput.error(DiagnosticReporter.render_traversal_blocked(path)) unless shape_ok
114
116
 
115
117
  # NB: reset_baseline defaults to false on purpose. The buffer only
116
118
  # replaces the tracked baseline for files that have no baseline yet
@@ -137,6 +137,12 @@ module Rubik
137
137
  # GoalStateAdapter precedent — a second registration would shadow this
138
138
  # one).
139
139
  class SubagentTranscriptAdapter
140
+ FRAGMENT_PARAM_KEYS = ["cursor", "limit", "snapshot"].freeze
141
+ FRAGMENT_SHAPES = {
142
+ "cursor" => /\A\d+\z/,
143
+ "snapshot" => /\A[a-z][a-z0-9_]*:[0-9a-f]{16}\z/
144
+ }.freeze
145
+
140
146
  def match?(uri)
141
147
  Rubik::Uris::SUBAGENT_TRANSCRIPT.match?(uri) || Rubik::Uris::SUBAGENT_RESULT.match?(uri)
142
148
  end
@@ -180,12 +186,26 @@ module Rubik
180
186
  Rubik::Orchestrator::Subagent::TranscriptReader.render_page(page)
181
187
  end
182
188
 
183
- # Fragment grammar: "#cursor=N&snapshot=TOK" — values are charset-safe
184
- # (digits / "live:hex"), so no percent-decoding is needed.
189
+ # Fragment grammar: "#cursor=N&limit=N&snapshot=SOURCE:HEX". Unknown
190
+ # keys and malformed values are dropped (the reader falls back to its
191
+ # own defaults) — no fragment text ever reaches the reader unchecked.
185
192
  def fragment_params(uri)
186
193
  uri.split("#", 2)[1].to_s.split("&").each_with_object({}) do |pair, acc|
187
194
  key, value = pair.split("=", 2)
188
- acc[key] = value if key && !key.empty? && value
195
+ next unless key && value && valid_fragment_param?(key, value)
196
+
197
+ acc[key] = value
198
+ end
199
+ end
200
+
201
+ def valid_fragment_param?(key, value)
202
+ return false unless FRAGMENT_PARAM_KEYS.include?(key)
203
+
204
+ case key
205
+ when "limit"
206
+ value.match?(/\A\d+\z/) && value.to_i.between?(1, Rubik::Orchestrator::Subagent::TranscriptReader::MAX_PAGE_CHARS)
207
+ else
208
+ FRAGMENT_SHAPES.fetch(key).match?(value)
189
209
  end
190
210
  end
191
211
 
data/lib/rubik/version.rb CHANGED
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Rubik
4
- VERSION = "0.15.1"
4
+ VERSION = "0.15.3"
5
5
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: rubik
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.15.1
4
+ version: 0.15.3
5
5
  platform: ruby
6
6
  authors:
7
7
  - Özgür Ulukır