rubik 0.13.0 → 0.14.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 (101) hide show
  1. checksums.yaml +4 -4
  2. data/ATTRIBUTION.md +1 -1
  3. data/CHANGELOG.md +34 -1
  4. data/lib/rubik/ast/c_extractor.rb +1 -1
  5. data/lib/rubik/ast/graph.rb +38 -57
  6. data/lib/rubik/ast/graph_extensions.rb +57 -15
  7. data/lib/rubik/ast/ruby_extractor.rb +4 -0
  8. data/lib/rubik/ast/treesitter/c_walker.rb +11 -3
  9. data/lib/rubik/buffer/manager.rb +33 -11
  10. data/lib/rubik/buffer/snapshot.rb +23 -3
  11. data/lib/rubik/cli/connect.rb +3 -5
  12. data/lib/rubik/config/defaults.rb +3 -7
  13. data/lib/rubik/config/env_guard.rb +43 -0
  14. data/lib/rubik/config/schema.rb +7 -1
  15. data/lib/rubik/config/secret_policy.rb +6 -5
  16. data/lib/rubik/config.rb +1 -1
  17. data/lib/rubik/connect/models_dev.rb +9 -0
  18. data/lib/rubik/connect/probes.rb +9 -2
  19. data/lib/rubik/connect/wizard.rb +108 -56
  20. data/lib/rubik/context/repo_context_reader.rb +8 -4
  21. data/lib/rubik/llm/chunk_assembler.rb +12 -1
  22. data/lib/rubik/llm/formatter.rb +14 -0
  23. data/lib/rubik/llm/provider_key.rb +32 -0
  24. data/lib/rubik/llm/registry.rb +18 -2
  25. data/lib/rubik/llm/router.rb +19 -1
  26. data/lib/rubik/llm/session_header.rb +128 -0
  27. data/lib/rubik/llm/sse_parser.rb +57 -10
  28. data/lib/rubik/lsp/client.rb +11 -5
  29. data/lib/rubik/lsp/transport.rb +17 -7
  30. data/lib/rubik/mcp/transport/stdio.rb +42 -4
  31. data/lib/rubik/orchestrator/continuation_manager.rb +14 -5
  32. data/lib/rubik/orchestrator/goal_ledger/ledger.rb +18 -2
  33. data/lib/rubik/orchestrator/goal_ledger/observation_projection.rb +13 -4
  34. data/lib/rubik/orchestrator/goal_ledger/validator.rb +46 -7
  35. data/lib/rubik/orchestrator/goal_ledger/verifier.rb +8 -1
  36. data/lib/rubik/orchestrator/goal_session.rb +4 -4
  37. data/lib/rubik/orchestrator/loop.rb +8 -11
  38. data/lib/rubik/orchestrator/provider_resolver.rb +29 -6
  39. data/lib/rubik/orchestrator/step_executor.rb +17 -2
  40. data/lib/rubik/orchestrator/subagent/instance.rb +24 -1
  41. data/lib/rubik/orchestrator/subagent/notices.rb +1 -1
  42. data/lib/rubik/orchestrator/subagent/reaper.rb +21 -2
  43. data/lib/rubik/orchestrator/subagent/start_gate.rb +1 -1
  44. data/lib/rubik/orchestrator/subagent/step_runner.rb +7 -7
  45. data/lib/rubik/orchestrator/subagent/supervisor.rb +10 -3
  46. data/lib/rubik/orchestrator/turn_executor/user_channel.rb +27 -5
  47. data/lib/rubik/orchestrator/turn_executor.rb +24 -8
  48. data/lib/rubik/platform/filesystem.rb +52 -24
  49. data/lib/rubik/plugin/storage.rb +20 -0
  50. data/lib/rubik/prompt/context_builder.rb +2 -1
  51. data/lib/rubik/repair/loop.rb +22 -2
  52. data/lib/rubik/repl/commands/agent_context.rb +1 -1
  53. data/lib/rubik/repl/commands/agent_execution.rb +20 -15
  54. data/lib/rubik/repl/commands/buffer.rb +15 -0
  55. data/lib/rubik/repl/commands/connect.rb +0 -1
  56. data/lib/rubik/repl/commands/lsp.rb +1 -1
  57. data/lib/rubik/repl/commands/plugins.rb +31 -31
  58. data/lib/rubik/repl/commands/session.rb +5 -5
  59. data/lib/rubik/repl/commands/workspace.rb +4 -4
  60. data/lib/rubik/repl/input_execution.rb +30 -29
  61. data/lib/rubik/repl/input_loop.rb +9 -4
  62. data/lib/rubik/repl/lifecycle.rb +1 -2
  63. data/lib/rubik/repl/notice_router.rb +11 -5
  64. data/lib/rubik/repl/paste_support.rb +1 -1
  65. data/lib/rubik/repl/prompt_grace.rb +3 -3
  66. data/lib/rubik/repl/shell.rb +10 -2
  67. data/lib/rubik/repl/turn_recorder.rb +14 -3
  68. data/lib/rubik/runtime/context.rb +33 -27
  69. data/lib/rubik/runtime/manager.rb +23 -15
  70. data/lib/rubik/sandbox/driver/bubblewrap.rb +58 -8
  71. data/lib/rubik/sandbox/driver/process.rb +32 -1
  72. data/lib/rubik/sandbox/runner.rb +9 -1
  73. data/lib/rubik/security/classifier/classifier.rb +147 -13
  74. data/lib/rubik/security/classifier/commands/docker.yaml +1 -1
  75. data/lib/rubik/security/classifier/commands/git.yaml +27 -1
  76. data/lib/rubik/security/classifier/commands/sed.yaml +3 -3
  77. data/lib/rubik/security/classifier/database.rb +2 -2
  78. data/lib/rubik/security/command_gate.rb +8 -1
  79. data/lib/rubik/security/redactor.rb +62 -19
  80. data/lib/rubik/session/recorder.rb +13 -18
  81. data/lib/rubik/session/replayer.rb +29 -7
  82. data/lib/rubik/storage/store.rb +19 -5
  83. data/lib/rubik/tools/builtins/exec.rb +1 -1
  84. data/lib/rubik/tools/builtins/files.rb +8 -12
  85. data/lib/rubik/tools/builtins/grep.rb +3 -2
  86. data/lib/rubik/tools/builtins/lsp.rb +31 -7
  87. data/lib/rubik/tools/builtins/show_file.rb +1 -1
  88. data/lib/rubik/tools/builtins/synthesis.rb +4 -4
  89. data/lib/rubik/tools/result_normalizer.rb +1 -1
  90. data/lib/rubik/ui/banner.rb +3 -3
  91. data/lib/rubik/ui/dialog.rb +10 -7
  92. data/lib/rubik/ui/diff_viewer.rb +4 -4
  93. data/lib/rubik/ui/frame.rb +13 -3
  94. data/lib/rubik/ui/markdown_stream.rb +8 -2
  95. data/lib/rubik/ui/panel.rb +11 -11
  96. data/lib/rubik/ui/renderer.rb +6 -6
  97. data/lib/rubik/ui/spinner.rb +1 -1
  98. data/lib/rubik/ui/statusline.rb +3 -3
  99. data/lib/rubik/ui/theme.rb +1 -1
  100. data/lib/rubik/version.rb +1 -1
  101. metadata +4 -1
@@ -10,6 +10,7 @@ require_relative "budget_manager"
10
10
  require_relative "stream_manager"
11
11
  require_relative "provider_resolver"
12
12
  require_relative "provider_recovery"
13
+ require_relative "../llm/session_header"
13
14
  require_relative "continuation_manager"
14
15
  require_relative "goal_wait"
15
16
  require_relative "resume_window"
@@ -49,8 +50,6 @@ module Rubik
49
50
  # in between would make prompt and execution disagree.
50
51
  @shell = shell
51
52
  @buffer_manager = shell&.buffer_manager
52
- @snapshot_store = shell&.snapshot_store
53
- @context_index = shell&.context_index
54
53
  @lsp_manager = shell&.lsp_manager
55
54
  @config = shell&.config
56
55
  @root_dir = File.expand_path(shell&.buffer_manager&.root_dir || Dir.pwd)
@@ -471,15 +470,13 @@ module Rubik
471
470
  effective_opts[:timeout] ||= effective_opts[:stream_timeout]
472
471
  # llm.* retry knobs join the timeout bridge above (per-call opts win).
473
472
  provider_resolver.apply_retry_defaults(effective_opts)
474
- # Plan 90 completion: the llm.thinking_budget_ratio / llm.reasoning_effort
475
- # knobs reach the adapters only through this bridge. Both default to nil
476
- # (never sent); the key must stay ABSENT when unset — openai_compatible's
477
- # reasoning_model? tests opts.key?(:reasoning_effort), so even a nil
478
- # value would flip every model onto the reasoning payload branch.
479
- ratio = provider_llm_config("thinking_budget_ratio", nil)
480
- effective_opts[:thinking_budget_ratio] ||= ratio if ratio
481
- effort = provider_llm_config("reasoning_effort", nil)
482
- effective_opts[:reasoning_effort] ||= effort if effort
473
+ provider_resolver.apply_reasoning_knobs(effective_opts)
474
+ # Per-provider session header (opencode-style hard-400 gateways): one
475
+ # call before the stream/batch branch covers both wire exits; the
476
+ # identity is the shell coeffect (same anchor as the subagent lane).
477
+ provider_resolver.apply_session_header!(
478
+ effective_opts, Rubik::LLM::SessionHeader.session_key_from_context(@runtime_manager&.context)
479
+ )
483
480
 
484
481
  if streaming_enabled && @provider.respond_to?(:stream_chat)
485
482
  @stream_manager.execute_streaming_request(effective_opts)
@@ -1,6 +1,8 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "../config/defaults"
4
+ require_relative "../llm/provider_key"
5
+ require_relative "../llm/session_header"
4
6
  require_relative "../storage/layout"
5
7
 
6
8
  module Rubik
@@ -35,13 +37,11 @@ module Rubik
35
37
  # else the class name derived the way builtin providers are registered
36
38
  # (Rubik::LLM::OllamaProvider -> "ollama"). An empty name counts as
37
39
  # unnamed, so instances built outside the registry keep falling back.
40
+ # Pure delegation since issue #534: the derivation itself lives in
41
+ # Rubik::LLM::ProviderKey (single source of truth, shared with
42
+ # Router#stream_chat's opt-in session-header injection).
38
43
  def registry_key
39
- explicit = @provider.respond_to?(:name) ? @provider.name.to_s.downcase : ""
40
- return explicit unless explicit.empty?
41
-
42
- klass_name = @provider.class.name
43
- base = klass_name&.split("::")&.last
44
- base&.delete_suffix("Provider")&.downcase
44
+ Rubik::LLM::ProviderKey.derive(@provider)
45
45
  end
46
46
 
47
47
  # Per-provider llm.* override: providers.<key>.<field> beats the global
@@ -78,6 +78,29 @@ module Rubik
78
78
  end
79
79
  opts
80
80
  end
81
+
82
+ # Plan 90 completion (moved here from Loop's request path to keep
83
+ # loop.rb under its coordinator cap): the llm.thinking_budget_ratio /
84
+ # llm.reasoning_effort knobs reach the adapters only through this
85
+ # bridge. Both default to nil (never sent); the key must stay ABSENT
86
+ # when unset — openai_compatible's reasoning_model? tests
87
+ # opts.key?(:reasoning_effort), so even a nil value would flip every
88
+ # model onto the reasoning payload branch.
89
+ def apply_reasoning_knobs(opts)
90
+ ratio = llm_config("thinking_budget_ratio", nil)
91
+ opts[:thinking_budget_ratio] ||= ratio if ratio
92
+ effort = llm_config("reasoning_effort", nil)
93
+ opts[:reasoning_effort] ||= effort if effort
94
+ opts
95
+ end
96
+
97
+ # Per-provider session header (opencode-style hard-400 gateways): the
98
+ # lane supplies only the conversation identity; knob lookup, provider
99
+ # key and the explicit-beats-automatic rule live in SessionHeader. The
100
+ # :headers key stays ABSENT when the knob or the identity is unset.
101
+ def apply_session_header!(opts, session_key)
102
+ Rubik::LLM::SessionHeader.apply!(opts, provider_key: registry_key, config: @config, session_key: session_key)
103
+ end
81
104
  end
82
105
  end
83
106
  end
@@ -49,7 +49,7 @@ module Rubik
49
49
 
50
50
  finish_call = (tool_instance.respond_to?(:terminal?) && tool_instance.terminal?) ||
51
51
  canonical_name == "finish" # unresolved case variant degrades to the name compare
52
- return handle_finish_tool(tool_args, text_resp, auto_apply_mode) if finish_call
52
+ return handle_finish_tool(tool_args, text_resp, auto_apply_mode, call_id) if finish_call
53
53
 
54
54
  # Maestro gate: maestro'nun doğrudan yürütme araçları reddedilir
55
55
  # (detay ve config semantics: maestro_gate.rb).
@@ -64,7 +64,7 @@ module Rubik
64
64
  end
65
65
  end
66
66
 
67
- def handle_finish_tool(tool_args, text_resp, auto_apply_mode = nil)
67
+ def handle_finish_tool(tool_args, text_resp, auto_apply_mode = nil, call_id = nil)
68
68
  if AutoApply.apply?(@deps.config, trigger: :finish, mode: auto_apply_mode) && @deps.buffer_manager&.dirty?
69
69
  applied = AutoApply.apply_and_sync(@deps.buffer_manager, @deps.shell)
70
70
  @deps.on_step&.call(type: :auto_apply, reason: "finish", files: applied, step: @deps.step_count, max_steps: @deps.max_steps)
@@ -81,6 +81,15 @@ module Rubik
81
81
  # turns already printed it above, batch turns render right below.
82
82
  @deps.on_step&.call(type: :finish, message: final_msg, streamed: @deps.last_turn_streamed == true,
83
83
  step: @deps.step_count, max_steps: @deps.max_steps)
84
+ # The assistant row carries the finish tool_use; it needs a pairing
85
+ # tool row or strict providers reject the next request (issue #548).
86
+ # The deferred-goal path in UserChannel writes the same shape.
87
+ if call_id
88
+ Rubik::Orchestrator::ToolHistory.write(
89
+ @deps.history, tool_call_id: call_id, tool_name: "finish",
90
+ status: :ok, duration_ms: 0.0, content: final_msg.to_s
91
+ )
92
+ end
84
93
  # streamed must reflect the FINISHING turn's reality: its text may
85
94
  # have been streamed as chunks before the finish call. A hardcoded
86
95
  # false made the free-text render treat an already-printed answer as
@@ -127,6 +136,12 @@ module Rubik
127
136
  @deps.record_invalid_tool!
128
137
  @deps.activity.record(tool_name, {}, :error) if @deps.respond_to?(:activity)
129
138
  if @deps.invalid_tool_count >= 2
139
+ # The first strike wrote its row; the terminal strike must too, or
140
+ # the invalid tool_use id stays orphaned in the assistant row (#548).
141
+ Rubik::Orchestrator::ToolHistory.write(
142
+ @deps.history, tool_call_id: call_id, tool_name: tool_name,
143
+ status: :error, duration_ms: 0.0, content: "Repeated invalid tool call '#{tool_name}'"
144
+ )
130
145
  return { ok: false, error: "Repeated invalid tool call '#{tool_name}'", steps: @deps.step_count,
131
146
  tokens: @deps.total_tokens, loop_instance: @deps.loop_instance }
132
147
  end
@@ -111,6 +111,7 @@ module Rubik
111
111
  @budget_cond = @monitor.new_cond
112
112
  @error_cond = @monitor.new_cond
113
113
  @context_cleaned_up = false
114
+ @archive_retries = 0
114
115
  @thread = nil
115
116
  @start_gate = nil
116
117
  @start_aborted = false
@@ -252,6 +253,15 @@ module Rubik
252
253
  end
253
254
  end
254
255
 
256
+ # Deadline for the budget-exhausted park, mirroring error_wait_timeout
257
+ # (issue #553). A non-positive configured value falls back to the
258
+ # resilience default so a parked worker can never wait unbounded.
259
+ def budget_exhausted_ttl
260
+ raw = Rubik::Storage::Layout.config_get(@config, "subagents.error_wait_timeout", nil)
261
+ ttl = raw.nil? ? Resilience::DEFAULT_ERROR_WAIT_TIMEOUT : raw.to_f
262
+ ttl.positive? ? ttl : Resilience::DEFAULT_ERROR_WAIT_TIMEOUT
263
+ end
264
+
255
265
  def pause_and_await_budget_expansion!(wait_timeout = nil)
256
266
  timeout = wait_timeout || Rubik::Storage::Layout.config_get(@config, "subagents.budget_wait_timeout", 180) || 180
257
267
  payload = nil
@@ -283,7 +293,20 @@ module Rubik
283
293
  Notices.emit(@event_bus, Notices::COMPLETED_EVENT, exhausted_payload) if exhausted_payload
284
294
 
285
295
  @monitor.synchronize do
286
- @budget_cond.wait while @state == :budget_exhausted
296
+ # Bounded parked pool (#553): an exhausted worker used to wait with
297
+ # NO deadline. While parked, active? excluded it from concurrency
298
+ # accounting and terminal_and_settled? excluded it from reaping, so
299
+ # an unanswered grant request leaked a live thread forever. Mirror
300
+ # the error-pause expiry: after error_wait_timeout with no grant,
301
+ # fail the run so it becomes terminal and reapable.
302
+ exhausted_ttl = budget_exhausted_ttl
303
+ @budget_cond.wait(exhausted_ttl) if @state == :budget_exhausted
304
+ if @state == :budget_exhausted
305
+ transition!(:failed)
306
+ @last_error ||= "Budget exhausted and no grant arrived within #{exhausted_ttl}s"
307
+ @unit&.sync_state!
308
+ return false
309
+ end
287
310
  return false if terminal?
288
311
 
289
312
  transition!(:running)
@@ -74,7 +74,7 @@ module Rubik
74
74
  end
75
75
 
76
76
  def normalize(event_name, payload)
77
- return nil if SILENT_ROLES.include?(payload[:role].to_s)
77
+ return nil if SILENT_ROLES.any? { |role| role.downcase == payload[:role].to_s.downcase.strip }
78
78
 
79
79
  kind = EVENTS[event_name.to_sym]
80
80
  return nil unless kind
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "../../log"
3
4
  require_relative "../../platform"
4
5
  require_relative "../../storage/layout"
5
6
 
@@ -13,13 +14,31 @@ module Rubik
13
14
  # ASLA reap edilmez: thread canlıdır (condvar park), resume hakları
14
15
  # bozulmaz.
15
16
  module Reaper
17
+ # Bounded transcript-save retry policy (#553): a failed save! returns
18
+ # nil and leaves no file, which previously made archive! return false
19
+ # forever — the instance was unreapable and its history leaked. After
20
+ # this many failed sweeps we reap WITH A WARNING; the save failure is
21
+ # still observable via last_error, and liveness beats a stuck tombstone.
22
+ TRANSCRIPT_ARCHIVE_MAX_RETRIES = 3
23
+
16
24
  def archived? = !!@archived
17
25
 
18
26
  # History yalnız transcript diske DURABLY yazıldıysa silinir —
19
- # dosya yoksa reap sonraki süpürmeye kalır (yarım tasfiye yok).
27
+ # dosya yoksa reap sonraki süpürmeye kalır (yarım tasfiye yok). After
28
+ # TRANSCRIPT_ARCHIVE_MAX_RETRIES the durability gate is released with
29
+ # a warning so a permanently-failing save cannot strand the instance.
20
30
  def archive!
21
31
  @monitor.synchronize do
22
- return false unless File.exist?(@transcript_uri.to_s)
32
+ unless File.exist?(@transcript_uri.to_s)
33
+ @archive_retries = (@archive_retries || 0) + 1
34
+ if @archive_retries < TRANSCRIPT_ARCHIVE_MAX_RETRIES
35
+ return false # transient: leave it for the next sweep
36
+ end
37
+
38
+ Rubik::Log.warn(:orchestrator,
39
+ "[Reaper] reaping #{@id} without a durable transcript after #{@archive_retries} attempts " \
40
+ "(last_error: #{@last_error.inspect})")
41
+ end
23
42
 
24
43
  @history.replace([])
25
44
  @archived = true
@@ -86,7 +86,7 @@ module Rubik
86
86
  thread.join(0.5)
87
87
  if thread.alive?
88
88
  thread.kill
89
- thread.join
89
+ thread.join(0.5) # bounded: a stuck inverse must not hang rollback (#553)
90
90
  end
91
91
  end
92
92
  cleanup_context
@@ -1,7 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "json"
4
- require_relative "../../config/defaults"
5
4
  require_relative "../../errors"
6
5
  require_relative "../../prompt"
7
6
  require_relative "../../platform"
@@ -9,6 +8,8 @@ require_relative "../../security/redactor"
9
8
  require_relative "../../tools/truncator"
10
9
  require_relative "../../uris"
11
10
  require_relative "../provider_recovery"
11
+ require_relative "../provider_resolver"
12
+ require_relative "../../llm/session_header"
12
13
  require_relative "../../storage/layout"
13
14
  require_relative "../auto_apply"
14
15
  require_relative "../tool_call_id"
@@ -114,12 +115,11 @@ module Rubik
114
115
  effective_opts[:open_timeout] ||= ProviderRecovery::DEFAULT_OPEN_TIMEOUT
115
116
  effective_opts[:context_limit] ||= @context_limit if @context_limit
116
117
  effective_opts[:max_tokens] ||= @max_output_tokens if @max_output_tokens&.positive?
117
- # Same llm.* transport-resilience knobs as the root loop, so a
118
- # subagent's HTTP retries obey operator config rather than only the
119
- # post_json built-ins. An explicit per-call value still wins.
120
- Rubik::Config::Defaults::LLM_RETRY_DEFAULTS.each do |key, fallback|
121
- effective_opts[key.to_sym] ||= Rubik::Storage::Layout.config_get(@config, "llm.#{key}", fallback)
122
- end
118
+ # The root loop's resolution seam: provider-scoped llm.* retry knobs plus
119
+ # the session header (identity: the shell coeffect — same conversation).
120
+ resolver = Rubik::Orchestrator::ProviderResolver.new(provider: @provider, config: @config)
121
+ resolver.apply_retry_defaults(effective_opts)
122
+ resolver.apply_session_header!(effective_opts, Rubik::LLM::SessionHeader.session_key_from_context(@context))
123
123
 
124
124
  # Operation telemetry (issue #126): the model wait is observable
125
125
  # while it lasts (status shows kind/name/elapsed) and its duration
@@ -154,10 +154,17 @@ module Rubik
154
154
  def kill_all(parent_id: nil)
155
155
  cancelled = []
156
156
  @monitor.synchronize do
157
- cancelled.concat(cancel_dependents_of(parent_id ? [] : @instances.keys + @deferred.keys))
157
+ # Route through kill_locked (not a bare Instance#kill) so the
158
+ # cascade reaches children and the dependency DAG's queued
159
+ # dependents are cancelled to a fixed point (#553) — otherwise a
160
+ # killed predecessor leaves its dependents stuck in @deferred.
161
+ ids = if parent_id
162
+ @instances.values.select { |i| i.parent_id == parent_id.to_s }.map(&:id)
163
+ else
164
+ @instances.keys + @deferred.keys
165
+ end
166
+ ids.each { |id| kill_locked(id.to_s, true, cancelled) }
158
167
  @deferred.clear if parent_id.nil?
159
- targets = parent_id ? @instances.values.select { |i| i.parent_id == parent_id.to_s } : @instances.values
160
- targets.each(&:kill)
161
168
  true
162
169
  end
163
170
  announce_cancellations(cancelled)
@@ -55,9 +55,23 @@ module Rubik
55
55
  # accumulated partial text and resets the buffer.
56
56
  def final_text(res, text)
57
57
  cm = @deps.loop_instance.continuation_manager
58
- return text if cm.continuation_buffer.empty?
58
+ # `text` is the executor's already-sanitized (and stripped)
59
+ # response. Use it as-is for a normal turn; the stitching branch
60
+ # below sanitizes raw res.text separately (issue #547).
61
+ safe_text = Platform.safe_utf8(text).to_s
62
+ if cm.continuation_buffer.empty?
63
+ # A response without a pending truncation closes the consecutive
64
+ # truncation chain (issue #549). stitch_and_reset covers the other
65
+ # branch; this keeps the buffer itself intact.
66
+ cm.reset_strikes!
67
+ return safe_text
68
+ end
59
69
 
60
- cm.stitch_and_reset(res.text.to_s)
70
+ # Stitch the RAW response (sanitized): `text` was already stripped
71
+ # by TurnExecutor#call, which would eat the leading indentation of
72
+ # the continuation chunk (issue #547).
73
+ raw_text = res.respond_to?(:text) ? res.text : text
74
+ cm.stitch_and_reset(Platform.safe_utf8(raw_text).to_s)
61
75
  end
62
76
 
63
77
  def track_usage(res) = @deps.budget_manager.track_token_usage!(res)
@@ -66,13 +80,20 @@ module Rubik
66
80
  # truncation, append the partial thought/text rows plus the
67
81
  # targeted nudge, or return the diagnostic terminal when
68
82
  # auto-continue is disabled or the ceiling is exhausted.
69
- def handle_truncation(res, _text_resp, tool_calls, finish_reason)
83
+ def handle_truncation(res, text_resp, tool_calls, finish_reason)
70
84
  cm = @deps.loop_instance.continuation_manager
71
85
  return nil unless cm.truncation?(finish_reason)
72
86
 
87
+ # Sanitize the RAW response here rather than reusing the already
88
+ # stripped `text_resp`: the continuation buffer must keep the exact
89
+ # partial text (including its trailing newline) while invalid bytes
90
+ # echoed with finish_reason=length must not raise in
91
+ # ContinuationManager#classify_truncation (issue #547).
92
+ raw_text = res.respond_to?(:text) ? res.text : text_resp
93
+ safe_text = Platform.safe_utf8(raw_text).to_s
73
94
  trunc_action = cm.handle_truncation(
74
95
  finish_reason: finish_reason,
75
- text_resp: res.text.to_s,
96
+ text_resp: safe_text,
76
97
  tool_calls: tool_calls,
77
98
  res: res,
78
99
  max_tokens: @deps.max_output_tokens || @deps.safe_config("llm.default_max_output_tokens", 4096)
@@ -81,7 +102,8 @@ module Rubik
81
102
  if trunc_action[:continue]
82
103
  nudge_policy.reset!
83
104
  if trunc_action[:thought]
84
- @deps.history << { role: "assistant", content: nil, thought: trunc_action[:thought] }
105
+ thought = Platform.safe_utf8(trunc_action[:thought])
106
+ @deps.history << { role: "assistant", content: nil, thought: thought }
85
107
  elsif trunc_action[:partial_text]
86
108
  @deps.history << { role: "assistant", content: trunc_action[:partial_text] }
87
109
  end
@@ -223,11 +223,14 @@ module Rubik
223
223
 
224
224
  def tool_turn(res, text_resp, tool_calls)
225
225
  channel.nudge_policy.reset!
226
- channel.append_tool_call_row(channel.final_text(res, text_resp), tool_calls)
226
+ # One stitched text for the assistant row AND tool dispatch, so a
227
+ # bare finish after truncation sees the partial (issue #547).
228
+ final = channel.final_text(res, text_resp)
229
+ channel.append_tool_call_row(final, tool_calls)
227
230
  streamed = res.respond_to?(:streamed) && res.streamed == true
228
231
  channel.announce_llm_thought(text_resp, streamed: streamed) if !text_resp.empty? && tool_calls.none? { |tc| self.class.finish_call?(channel.tool_registry, tc) }
229
232
 
230
- tool_calls.each do |tc|
233
+ tool_calls.each_with_index do |tc, idx|
231
234
  # finish is exempt (pinned by test_orchestrator_stream): its args
232
235
  # are optional and the fallback text carries the message, so a
233
236
  # malformed finish must still complete the turn gracefully instead
@@ -236,8 +239,12 @@ module Rubik
236
239
  channel.malformed_args_row(tc)
237
240
  next
238
241
  end
239
- result = channel.execute_tool_call(tc, text_resp)
240
- return result if result
242
+ result = channel.execute_tool_call(tc, final)
243
+ next unless result
244
+
245
+ # Pair calls that follow a terminal one (issue #548).
246
+ tool_calls[(idx + 1)..]&.each { |later| channel.pair_skipped_tool_call(later) }
247
+ return result
241
248
  end
242
249
  nil
243
250
  end
@@ -335,10 +342,19 @@ module Rubik
335
342
  raise NotImplementedError, "channel must dispatch tool calls"
336
343
  end
337
344
 
338
- # Canonical error row for a tool call whose String args failed to
339
- # parse (issue #55 3.4): the model sees its own rejected payload,
340
- # the tool_call_id stays paired (strict providers 400 on orphaned
341
- # ids), and the tool never dispatches with degraded {} args.
345
+ # Pairing row for a skipped tool_use id (issue #548).
346
+ def pair_skipped_tool_call(tool_call)
347
+ ToolHistory.write(history,
348
+ tool_call_id: tool_call["id"],
349
+ tool_name: tool_call["tool"].to_s,
350
+ status: :error,
351
+ duration_ms: 0.0,
352
+ content: "Tool call was not executed: the turn completed on an earlier tool call.")
353
+ nil
354
+ end
355
+
356
+ # Canonical error row for unparsable String args (issue #55 3.4):
357
+ # echo the rejected payload, keep the tool_call_id paired.
342
358
  def malformed_args_row(tool_call)
343
359
  ToolHistory.write(history,
344
360
  tool_call_id: tool_call["id"],
@@ -1,5 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "securerandom"
4
+
3
5
  module Rubik
4
6
  module Platform
5
7
  # File system operations (atomic writes, newline normalization).
@@ -12,36 +14,62 @@ module Rubik
12
14
  def atomic_write(target_path, content)
13
15
  dir = File.dirname(target_path)
14
16
  FileUtils.mkdir_p(dir) unless File.directory?(dir)
15
- tmp_file = "#{target_path}.tmp.#{::Process.pid}.#{rand(1_000_000)}"
16
17
 
17
- File.open(tmp_file, "wb") do |f|
18
- f.write(content)
19
- f.flush
20
- begin
21
- f.fsync
22
- rescue StandardError, ScriptError
23
- nil
24
- end
18
+ # Preserve the target's permission bits (issue #543): File.open creates
19
+ # a 0644 temp file and rename keeps the temp's mode, so overwriting a
20
+ # 0600 secret would expose it and a 0755 script would lose +x. Capture
21
+ # the mode before writing and carry it onto the temp file before rename.
22
+ existing_mode = begin
23
+ stat = File.stat(target_path)
24
+ stat.mode & 0o7777 if stat.file?
25
+ rescue Errno::ENOENT
26
+ nil
25
27
  end
26
28
 
27
- # Atomic replace: rename tmp_file -> target_path without unlinking first
28
- # (closing TOCTOU). Retry for Windows transient locks.
29
- retries = 3
29
+ # O_EXCL refuses a pre-placed path (including a symlink) instead of
30
+ # following it, and the random suffix makes the temp name unpredictable.
31
+ # Together they close the TOCTOU/symlink redirection of issue #543.
32
+ tmp_file = "#{target_path}.tmp.#{::Process.pid}.#{SecureRandom.hex(12)}"
33
+ created = false
34
+
30
35
  begin
31
- File.rename(tmp_file, target_path)
32
- rescue SystemCallError => e
33
- if retries.positive?
34
- retries -= 1
35
- sleep 0.02
36
- retry
36
+ # Mode 0o600 keeps the in-flight temp private until the final chmod.
37
+ File.open(tmp_file, File::WRONLY | File::CREAT | File::EXCL | File::BINARY, 0o600) do |f|
38
+ created = true
39
+ f.write(content)
40
+ f.flush
41
+ begin
42
+ f.fsync
43
+ rescue StandardError, ScriptError
44
+ nil
45
+ end
37
46
  end
38
- debug_warn("atomic_write failed for #{target_path}: #{e.class}: #{e.message}")
39
- raise
40
- ensure
47
+
48
+ File.chmod(existing_mode, tmp_file) if existing_mode
49
+
50
+ # Atomic replace: rename tmp_file -> target_path without unlinking first
51
+ # (closing TOCTOU). Retry for Windows transient locks.
52
+ retries = 3
41
53
  begin
42
- FileUtils.rm_f(tmp_file)
43
- rescue StandardError, ScriptError
44
- nil
54
+ File.rename(tmp_file, target_path)
55
+ rescue SystemCallError => e
56
+ if retries.positive?
57
+ retries -= 1
58
+ sleep 0.02
59
+ retry
60
+ end
61
+ debug_warn("atomic_write failed for #{target_path}: #{e.class}: #{e.message}")
62
+ raise
63
+ end
64
+ ensure
65
+ # Only remove the temp file we created; never delete a pre-placed
66
+ # path (e.g. an attacker's symlink) that made O_EXCL fail.
67
+ if created
68
+ begin
69
+ FileUtils.rm_f(tmp_file)
70
+ rescue StandardError, ScriptError
71
+ nil
72
+ end
45
73
  end
46
74
  end
47
75
  end
@@ -189,6 +189,9 @@ module Rubik
189
189
 
190
190
  def remove_plugin(name, scope: :project)
191
191
  target_dir = scope.to_sym == :global ? global_plugins_dir : project_plugins_dir
192
+
193
+ return { ok: false, error: "Invalid plugin name: #{name.to_s.inspect}." } unless safe_plugin_name?(name, target_dir)
194
+
192
195
  file_path = File.join(target_dir, "#{name}.rb")
193
196
  dir_path = File.join(target_dir, name.to_s)
194
197
 
@@ -219,6 +222,23 @@ module Rubik
219
222
 
220
223
  private
221
224
 
225
+ # A plugin name must resolve to a single path component directly under
226
+ # 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.
230
+ def safe_plugin_name?(name, target_dir)
231
+ component = name.to_s
232
+ return false if component.empty? || component == "." || component == ".."
233
+ return false if component.match?(%r{[/\\\0]})
234
+
235
+ base = File.expand_path(target_dir)
236
+ candidate = File.expand_path(component, base)
237
+ candidate.start_with?("#{base}#{File::SEPARATOR}") && File.dirname(candidate) == base
238
+ rescue ArgumentError
239
+ false
240
+ end
241
+
222
242
  # The package root for a path inside the plugins dir: plugins/<first
223
243
  # segment> when that segment is a DIRECTORY (directory plugin); nil for
224
244
  # a single-file plugin. A path outside the plugins dir is not a package.
@@ -7,6 +7,7 @@ require_relative "../context/repo_context_reader"
7
7
  # this module is the assembler: structure + service data only.
8
8
  require_relative "doctrine"
9
9
  require_relative "services"
10
+ require_relative "../tools/builtins/lsp"
10
11
 
11
12
  module Rubik
12
13
  module Prompt
@@ -250,7 +251,7 @@ module Rubik
250
251
 
251
252
  all_diags.each do |fpath, diags|
252
253
  diags.each do |d|
253
- sev = d["severity"] == 1 ? "error" : "warning"
254
+ sev = Rubik::Tools::LSPSeverity.label(d["severity"])
254
255
  total_errors += 1 if sev == "error"
255
256
  start_line = (d.dig("range", "start", "line") || 0) + 1
256
257
  msg = Rubik::Platform.xml_escape(d["message"])
@@ -2,18 +2,22 @@
2
2
 
3
3
  require "json"
4
4
  require "tempfile"
5
+ require_relative "../llm/session_header"
6
+ require_relative "../orchestrator/provider_resolver"
5
7
 
6
8
  module Rubik
7
9
  module Repair
8
10
  class Loop
9
11
  attr_reader :max_attempts, :attempts_made, :config
10
12
 
11
- def initialize(provider:, buffer_manager:, snapshot_store:, adapter_registry:, max_attempts: nil, config: nil)
13
+ def initialize(provider:, buffer_manager:, snapshot_store:, adapter_registry:, max_attempts: nil, config: nil,
14
+ session_key: nil)
12
15
  @provider = provider
13
16
  @buffer_manager = buffer_manager
14
17
  @snapshot_store = snapshot_store
15
18
  @adapter_registry = adapter_registry
16
19
  @config = config
20
+ @session_key = session_key
17
21
  @max_attempts = (max_attempts || config&.fetch("repair.max_attempts", 3) || 3).to_i
18
22
  @attempts_made = 0
19
23
  end
@@ -21,15 +25,31 @@ module Rubik
21
25
  def repair(diagnostics, target_file, lang = :ruby)
22
26
  @attempts_made = 0
23
27
  current_diag = diagnostics
28
+ baseline_recorded = false
24
29
 
25
30
  while @attempts_made < @max_attempts
26
31
  @attempts_made += 1
27
32
 
33
+ # Capture the pre-repair state once so an aborted attempt restores
34
+ # pending edits instead of an empty buffer (issue #544).
35
+ unless baseline_recorded
36
+ @snapshot_store.record_baseline(@buffer_manager)
37
+ baseline_recorded = true
38
+ end
39
+
28
40
  @snapshot_store.create_snapshot(@buffer_manager)
29
41
 
30
42
  begin
31
43
  prompt = build_repair_prompt(current_diag, target_file, @attempts_made)
32
- res = @provider.complete([{ role: "user", content: prompt }])
44
+ # Same per-provider session header as every other lane — repair is
45
+ # auxiliary traffic on the SAME conversation for the gateway.
46
+ header_opts = Rubik::LLM::SessionHeader.apply!(
47
+ {},
48
+ provider_key: Rubik::Orchestrator::ProviderResolver.new(provider: @provider, config: @config).registry_key,
49
+ config: @config,
50
+ session_key: @session_key
51
+ )
52
+ res = @provider.complete([{ role: "user", content: prompt }], header_opts)
33
53
  proposed_code = extract_code(res.text)
34
54
 
35
55
  if proposed_code.empty?
@@ -202,7 +202,7 @@ module Rubik
202
202
  ctx.out.puts " • Default Task Max Steps : #{cur_max}"
203
203
  ctx.out.puts " • Goal Mode Max Steps : #{goal_max}"
204
204
  ctx.out.puts " • Plan Mode Max Steps : #{plan_max}"
205
- ctx.out.puts " • Warning Threshold : #{(warn_r.to_f * 100).to_i}% (#{(cur_max.to_i * warn_r.to_f).ceil}. adım)"
205
+ ctx.out.puts " • Warning Threshold : #{(warn_r.to_f * 100).to_i}% (step #{(cur_max.to_i * warn_r.to_f).ceil})"
206
206
  ctx.out.puts " • Ask Continue on Limit : #{ask_c}"
207
207
  elsif clean_args.first.downcase == "default"
208
208
  num = clean_args[1].to_i