rubik 0.11.0 → 0.13.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 (54) hide show
  1. checksums.yaml +4 -4
  2. data/ATTRIBUTION.md +1 -1
  3. data/CHANGELOG.md +94 -1
  4. data/bin/rubik +11 -1
  5. data/lib/rubik/buffer/manager.rb +3 -3
  6. data/lib/rubik/cli/connect.rb +51 -0
  7. data/lib/rubik/config/deep_ops.rb +3 -1
  8. data/lib/rubik/config/defaults.rb +9 -8
  9. data/lib/rubik/config/schema.rb +8 -0
  10. data/lib/rubik/config/secret_policy.rb +14 -5
  11. data/lib/rubik/config.rb +1 -1
  12. data/lib/rubik/connect/http.rb +85 -0
  13. data/lib/rubik/connect/models_dev.rb +164 -0
  14. data/lib/rubik/connect/probes.rb +96 -0
  15. data/lib/rubik/connect/prompt_ui.rb +139 -0
  16. data/lib/rubik/connect/wizard.rb +488 -0
  17. data/lib/rubik/connect.rb +7 -0
  18. data/lib/rubik/llm/anthropic.rb +2 -1
  19. data/lib/rubik/llm/client.rb +22 -6
  20. data/lib/rubik/llm/formatter.rb +4 -1
  21. data/lib/rubik/llm/ollama.rb +2 -1
  22. data/lib/rubik/llm/openai_compatible.rb +6 -2
  23. data/lib/rubik/llm/router.rb +6 -1
  24. data/lib/rubik/llm/sse_parser.rb +17 -14
  25. data/lib/rubik/mcp/manager.rb +14 -1
  26. data/lib/rubik/mcp/proxy_tool.rb +2 -2
  27. data/lib/rubik/mcp/transport/stdio.rb +3 -2
  28. data/lib/rubik/orchestrator/goal_state.rb +6 -2
  29. data/lib/rubik/orchestrator/loop.rb +30 -6
  30. data/lib/rubik/orchestrator/provider_resolver.rb +12 -0
  31. data/lib/rubik/orchestrator/subagent/step_runner.rb +7 -0
  32. data/lib/rubik/platform/filesystem.rb +2 -2
  33. data/lib/rubik/repair/loop.rb +1 -1
  34. data/lib/rubik/repl/commands/connect.rb +52 -0
  35. data/lib/rubik/repl/commands.rb +2 -0
  36. data/lib/rubik/repl/input_execution.rb +143 -4
  37. data/lib/rubik/repl/input_loop.rb +1 -0
  38. data/lib/rubik/repl/lifecycle.rb +39 -0
  39. data/lib/rubik/repl/shell.rb +9 -1
  40. data/lib/rubik/runtime/fiber.rb +1 -0
  41. data/lib/rubik/runtime/manager.rb +4 -1
  42. data/lib/rubik/runtime/task_manager.rb +3 -3
  43. data/lib/rubik/sandbox/driver/base.rb +7 -0
  44. data/lib/rubik/sandbox/driver/docker.rb +1 -4
  45. data/lib/rubik/sandbox/driver/podman.rb +1 -0
  46. data/lib/rubik/sandbox/runner.rb +1 -1
  47. data/lib/rubik/security/classifier/classifier.rb +2 -0
  48. data/lib/rubik/storage/store.rb +4 -1
  49. data/lib/rubik/tools/registry.rb +36 -16
  50. data/lib/rubik/ui/capability.rb +6 -4
  51. data/lib/rubik/ui/markdown_stream.rb +1 -0
  52. data/lib/rubik/ui/renderer.rb +4 -2
  53. data/lib/rubik/version.rb +1 -1
  54. metadata +9 -1
@@ -13,21 +13,21 @@ module Rubik
13
13
  # internal buffer until the next feed.
14
14
  class SSEParser
15
15
  SSE_EVENT_SEP = /\r\n\r\n|\n\n|\r\n\n|\n\r\n|\r\r/
16
+ SSE_EVENT_SEP_BIN = Regexp.new(SSE_EVENT_SEP.source.b, Regexp::NOENCODING)
16
17
  SSE_TERMINATOR = "\n\n"
17
18
  NDJSON_TERMINATOR = "\n"
18
19
 
19
20
  def initialize(terminator: SSE_TERMINATOR)
20
21
  @terminator = terminator
22
+ @terminator_bin = terminator.is_a?(String) ? terminator.b : terminator
21
23
  @sse_mode = @terminator == SSE_TERMINATOR || @terminator == SSE_EVENT_SEP
22
- @buffer = String.new(encoding: Encoding::UTF_8)
24
+ @buffer = String.new(encoding: Encoding::ASCII_8BIT)
23
25
  end
24
26
 
25
27
  # Feed raw bytes; returns an array of complete events parsed from this
26
28
  # chunk. Partial events stay in the buffer.
27
29
  def feed(chunk_bytes)
28
- incoming = chunk_bytes.to_s.dup.force_encoding(Encoding::UTF_8)
29
- incoming = incoming.scrub unless incoming.valid_encoding?
30
- @buffer << incoming
30
+ @buffer << chunk_bytes.to_s.b
31
31
  drain_complete_events(final: false)
32
32
  end
33
33
 
@@ -39,7 +39,7 @@ module Rubik
39
39
 
40
40
  unless @buffer.empty?
41
41
  remaining = @buffer.dup
42
- @buffer = String.new(encoding: Encoding::UTF_8)
42
+ @buffer = String.new(encoding: Encoding::ASCII_8BIT)
43
43
  parsed = parse_event(remaining)
44
44
  events << parsed if parsed
45
45
  end
@@ -58,18 +58,18 @@ module Rubik
58
58
  def drain_complete_events(final:)
59
59
  events = []
60
60
  if @sse_mode
61
- while (m = @buffer.match(SSE_EVENT_SEP))
62
- break if !final && m.end(0) == @buffer.bytesize && @buffer.end_with?("\r")
61
+ while (m = @buffer.match(SSE_EVENT_SEP_BIN))
62
+ break if !final && m.end(0) == @buffer.bytesize && @buffer.end_with?("\r".b)
63
63
 
64
- event_block = @buffer[0...m.begin(0)]
65
- @buffer = @buffer[m.end(0)..] || String.new(encoding: Encoding::UTF_8)
64
+ event_block = @buffer.byteslice(0, m.begin(0))
65
+ @buffer = @buffer.byteslice(m.end(0)..-1) || String.new(encoding: Encoding::ASCII_8BIT)
66
66
  parsed = parse_event(event_block)
67
67
  events << parsed if parsed
68
68
  end
69
69
  else
70
- while (idx = @buffer.index(@terminator))
71
- event_block = @buffer[0...idx]
72
- @buffer = @buffer[(idx + @terminator.length)..] || String.new(encoding: Encoding::UTF_8)
70
+ while (idx = @buffer.index(@terminator_bin))
71
+ event_block = @buffer.byteslice(0, idx)
72
+ @buffer = @buffer.byteslice((idx + @terminator_bin.bytesize)..-1) || String.new(encoding: Encoding::ASCII_8BIT)
73
73
  parsed = parse_event(event_block)
74
74
  events << parsed if parsed
75
75
  end
@@ -79,9 +79,12 @@ module Rubik
79
79
 
80
80
  def parse_event(block)
81
81
  return nil if block.nil?
82
- return { type: "message", data: block.to_s.chomp } unless @sse_mode
83
82
 
84
- lines = block.to_s.split(/\r\n|\r|\n/)
83
+ utf8 = block.to_s.dup.force_encoding(Encoding::UTF_8)
84
+ utf8 = utf8.scrub unless utf8.valid_encoding?
85
+ return { type: "message", data: utf8.chomp } unless @sse_mode
86
+
87
+ lines = utf8.split(/\r\n|\r|\n/)
85
88
  return nil if lines.empty?
86
89
 
87
90
  event_type = "message"
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "digest"
3
4
  require "monitor"
4
5
  require_relative "boot_lifecycle"
5
6
  require_relative "../storage/layout"
@@ -73,6 +74,8 @@ module Rubik
73
74
  persist_res = { ok: true }
74
75
 
75
76
  @monitor.synchronize do
77
+ disable_server(name_str) if @statuses[name_str] == :active || @clients.key?(name_str) || @contexts.key?(name_str)
78
+
76
79
  @servers[name_str] = parsed_defn
77
80
  @statuses[name_str] ||= :disabled
78
81
 
@@ -215,9 +218,19 @@ module Rubik
215
218
  if @tools_registry
216
219
  tools.each do |tdef|
217
220
  proxy = Rubik::MCP::ProxyTool.new(server_name: name_str, tool_def: tdef, client: client)
221
+ if @tools_registry.respond_to?(:get) && @tools_registry.get(proxy.name)
222
+ digest = Digest::SHA256.hexdigest("#{name_str}\0#{proxy.original_name}")[0, 6]
223
+ unique_name = "#{proxy.name}_#{digest}"
224
+ counter = 2
225
+ while @tools_registry.get(unique_name)
226
+ unique_name = "#{proxy.name}_#{digest}_#{counter}"
227
+ counter += 1
228
+ end
229
+ proxy = Rubik::MCP::ProxyTool.new(server_name: name_str, tool_def: tdef, client: client, name: unique_name)
230
+ end
218
231
  @tools_registry.register(proxy, origin: :mcp)
219
232
  server_tools << proxy
220
- server_ctx.on_dispose { @tools_registry.unregister(proxy.name) }
233
+ server_ctx.on_dispose { @tools_registry.unregister(proxy.name, proxy) }
221
234
  end
222
235
  end
223
236
 
@@ -8,14 +8,14 @@ module Rubik
8
8
  class ProxyTool < Rubik::Tools::BaseTool
9
9
  attr_reader :server_name, :original_name, :client
10
10
 
11
- def initialize(server_name:, tool_def:, client:)
11
+ def initialize(server_name:, tool_def:, client:, name: nil)
12
12
  @server_name = server_name.to_s
13
13
  @client = client
14
14
  @original_name = (tool_def["name"] || tool_def[:name]).to_s
15
15
 
16
16
  sanitized_server = @server_name.downcase.gsub(/[^a-z0-9_]/, "_")
17
17
  sanitized_tool = @original_name.downcase.gsub(/[^a-z0-9_]/, "_")
18
- tool_name = "mcp_#{sanitized_server}_#{sanitized_tool}"
18
+ tool_name = name || "mcp_#{sanitized_server}_#{sanitized_tool}"
19
19
 
20
20
  raw_desc = (tool_def["description"] || tool_def[:description] || "").to_s.strip
21
21
  desc = raw_desc.empty? ? "[MCP: #{@server_name}] #{@original_name}" : "[MCP: #{@server_name}] #{raw_desc}"
@@ -19,8 +19,9 @@ module Rubik
19
19
  # Credential-shaped variable names stripped from the inherited host
20
20
  # environment when a server opts out with `inherit_env: false`. Only
21
21
  # the suffix shape is policy — the prefix is the provider's choice
22
- # (GITHUB_TOKEN, ANTHROPIC_API_KEY, ...), so we match it broadly.
23
- CREDENTIAL_ENV_PATTERN = /_(API_KEY|TOKEN|SECRET|PASSWORD)\z/i
22
+ # (GITHUB_TOKEN, ANTHROPIC_API_KEY, AWS_SECRET_ACCESS_KEY, GITHUB_PAT,
23
+ # DATABASE_URL, ...), so we match it broadly.
24
+ CREDENTIAL_ENV_PATTERN = /_(KEY|TOKEN|SECRET|PASSWORD|PAT)\z|\A(DATABASE|REDIS|MONGO|POSTGRES|MYSQL|AMQP)_URL\z|_(DATABASE|REDIS|CONNECTION)_URL\z/i
24
25
 
25
26
  attr_reader :command, :args, :env, :inherit_env, :root_dir, :running, :wait_thr
26
27
 
@@ -243,9 +243,13 @@ module Rubik
243
243
  def finish_unlocked!(status, tokens)
244
244
  @status = status
245
245
  @finished_at = Time.now
246
+ return if tokens.nil?
247
+
246
248
  t = tokens.to_h
247
- @tokens[:input] += t[:input].to_i
248
- @tokens[:output] += t[:output].to_i
249
+ @tokens = {
250
+ input: (t[:input] || t["input"]).to_i,
251
+ output: (t[:output] || t["output"]).to_i
252
+ }
249
253
  end
250
254
 
251
255
  def iso(time) = time ? time.utc.iso8601 : ""
@@ -146,6 +146,7 @@ module Rubik
146
146
 
147
147
  begin
148
148
  target_model = model || @model
149
+ @active_model = target_model
149
150
  opts = target_model ? { model: target_model } : {}
150
151
  opts[:tools] = @tool_registry.schemas unless plan_only
151
152
 
@@ -243,6 +244,29 @@ module Rubik
243
244
  end
244
245
  end
245
246
 
247
+ # Serbest-metin turn'i için hata-sonrası devam sözleşmesi: LLM hatasıyla
248
+ # ölen turn aynı Loop örneğinde, aynı @history ve adım bütçesiyle sürer
249
+ # (continue_loop/resume! ile aynı execute_steps yolu; run() ASLA çağrılmaz
250
+ # — sayaçların korunması sözleşmenin özüdür). on_step swap'ı sözleşmenin
251
+ # parçası: ölü turn'in handler'ı eski renderer closure'ını taşır.
252
+ def resume_turn!(reason: "llm_error_recovery", on_step: nil)
253
+ @on_step = on_step if on_step
254
+ # run()'ın ensure'i eski alt bağlamı imha etti; taze ctx.extend kur ve
255
+ # koşu sonunda imha et (§C scoped sub-context disiplini).
256
+ @loop_context&.dispose
257
+ @loop_context = @runtime_manager&.context&.extend
258
+ begin
259
+ # Plan 61 D-14 mold: marker kendi user mesajı olarak gider.
260
+ @history << { role: "user", content: "<turn_resumed reason=\"#{Rubik::Platform.xml_escape(reason.to_s)[0, 300]}\" " \
261
+ "step=\"#{@step_count}\" max_steps=\"#{@max_steps}\" message=\"The previous turn was interrupted by an LLM error. " \
262
+ "Resuming the SAME task with full context and step budget preserved. Continue working toward completion.\" />" }
263
+ execute_steps(opts: resume_request_opts)
264
+ ensure
265
+ @loop_context&.dispose
266
+ @loop_context = nil
267
+ end
268
+ end
269
+
246
270
  # Shared by both request paths (batch + streaming, Plan 63 Faz A):
247
271
  # compact the history in place and emit the :emergency_compact event
248
272
  # carrying the layer that produced the final history. Public because
@@ -321,7 +345,7 @@ module Rubik
321
345
  # continue_loop'un opts sözleşmesinin aynısı: model override'ı yok —
322
346
  # resume, koşunun başındaki modeliyle sürer.
323
347
  def resume_request_opts
324
- target_model = @model
348
+ target_model = @active_model || @model
325
349
  opts = target_model ? { model: target_model } : {}
326
350
  opts[:tools] = @tool_registry.schemas
327
351
  opts
@@ -436,17 +460,17 @@ module Rubik
436
460
  def send_llm_request_with_recovery(opts)
437
461
  streaming_enabled = opts.key?(:stream) ? (opts[:stream] == true) : (provider_llm_config("stream", true) != false)
438
462
 
439
- # Plan 61 D-1/D-3: the wire request must share the compaction math's
440
- # assumptions. Ollama needs context_limit (sent as num_ctx) or its
441
- # server silently clips the prompt head to the model default; strict
442
- # providers need max_tokens or output falls back to tiny defaults
443
- # (e.g. Anthropic's 1024).
463
+ # Plan 61 D-1/D-3: share the compaction math with the wire request —
464
+ # Ollama needs context_limit (num_ctx) or it clips the prompt head;
465
+ # strict providers need max_tokens or output falls back to ~1024.
444
466
  effective_opts = opts.key?(:on_retry) ? opts.dup : opts.merge(on_retry: @stream_manager.llm_retry_notifier)
445
467
  effective_opts[:context_limit] = @context_limit if @context_limit
446
468
  effective_opts[:max_tokens] = @max_output_tokens if @max_output_tokens&.positive?
447
469
  effective_opts[:stream_timeout] ||= provider_llm_config("stream_timeout", ProviderRecovery::STREAM_REQUEST_TIMEOUT)
448
470
  effective_opts[:open_timeout] ||= provider_llm_config("open_timeout", ProviderRecovery::DEFAULT_OPEN_TIMEOUT)
449
471
  effective_opts[:timeout] ||= effective_opts[:stream_timeout]
472
+ # llm.* retry knobs join the timeout bridge above (per-call opts win).
473
+ provider_resolver.apply_retry_defaults(effective_opts)
450
474
  # Plan 90 completion: the llm.thinking_budget_ratio / llm.reasoning_effort
451
475
  # knobs reach the adapters only through this bridge. Both default to nil
452
476
  # (never sent); the key must stay ABSENT when unset — openai_compatible's
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "../config/defaults"
3
4
  require_relative "../storage/layout"
4
5
 
5
6
  module Rubik
@@ -66,6 +67,17 @@ module Rubik
66
67
  rescue StandardError
67
68
  default
68
69
  end
70
+
71
+ # llm.* transport-resilience knobs (retry budgets, backoff, delay clamp)
72
+ # reach the provider opts through this same per-provider lookup. A value
73
+ # already set by the caller wins; unset keys fall back to the shared
74
+ # defaults in config/defaults.rb.
75
+ def apply_retry_defaults(opts)
76
+ Rubik::Config::Defaults::LLM_RETRY_DEFAULTS.each do |key, fallback|
77
+ opts[key.to_sym] ||= llm_config(key, fallback)
78
+ end
79
+ opts
80
+ end
69
81
  end
70
82
  end
71
83
  end
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "json"
4
+ require_relative "../../config/defaults"
4
5
  require_relative "../../errors"
5
6
  require_relative "../../prompt"
6
7
  require_relative "../../platform"
@@ -113,6 +114,12 @@ module Rubik
113
114
  effective_opts[:open_timeout] ||= ProviderRecovery::DEFAULT_OPEN_TIMEOUT
114
115
  effective_opts[:context_limit] ||= @context_limit if @context_limit
115
116
  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
116
123
 
117
124
  # Operation telemetry (issue #126): the model wait is observable
118
125
  # while it lasts (status shows kind/name/elapsed) and its duration
@@ -35,8 +35,8 @@ module Rubik
35
35
  sleep 0.02
36
36
  retry
37
37
  end
38
- debug_warn("atomic_write fallback for #{target_path}: #{e.class}: #{e.message}")
39
- File.binwrite(target_path, content)
38
+ debug_warn("atomic_write failed for #{target_path}: #{e.class}: #{e.message}")
39
+ raise
40
40
  ensure
41
41
  begin
42
42
  FileUtils.rm_f(tmp_file)
@@ -99,7 +99,7 @@ module Rubik
99
99
 
100
100
  def extract_code(text)
101
101
  if text.include?("```")
102
- text.split("```").at(1).to_s.sub(/^[a-z]+\n/, "").strip
102
+ text.split("```").at(1).to_s.sub(/\A[^\n]*\n/, "").strip
103
103
  else
104
104
  text.strip
105
105
  end
@@ -0,0 +1,52 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "base"
4
+ require_relative "../../connect"
5
+
6
+ module Rubik
7
+ module REPL
8
+ module Commands
9
+ # `!connect` — the in-REPL entry to the provider connect wizard.
10
+ # Unlike !provider add's :session default, !connect persists to
11
+ # :global by default: the wizard's purpose is durable setup, and a
12
+ # session-scoped provider silently vanishing on exit would undo the
13
+ # friction reduction this command exists for. --project/--global
14
+ # flags override, exactly like every other config-touching command.
15
+ module Connect
16
+ extend Base
17
+
18
+ USAGE_CONNECT = "Usage: !connect [--project|--global]"
19
+
20
+ def self.register(shell)
21
+ shell.register_command("connect",
22
+ description: "Interactive wizard: add an LLM provider (models.dev catalog, live key check) " \
23
+ "and bind model roles",
24
+ usage: USAGE_CONNECT) do |args, ctx|
25
+ # The wizard has no session tier: an explicit --session/-s would
26
+ # otherwise be silently coerced into the most persistent write
27
+ # the wizard can make. Honest refusal beats silent escalation.
28
+ if args.intersect?(["--session", "-s"])
29
+ ctx.out.puts USAGE_CONNECT
30
+ ctx.out.puts " !connect yalnızca kalıcı kapsamlara yazar; oturum-kapsamı için !provider add kullanın."
31
+ ctx.out.puts " !connect writes persistent scopes only; use !provider add for a session-scoped provider."
32
+ else
33
+ scope, _clean = Base.parse_scope(args)
34
+ scope = :global if scope == :session
35
+ result = invoke(ctx, scope)
36
+ ctx.out.puts USAGE_CONNECT if result[:reason] == :non_interactive
37
+ end
38
+ end
39
+ end
40
+
41
+ # ui:/probe: kwargs are test seams — shell-level tests inject a
42
+ # scripted PromptUI (and stubbed probes) instead of driving
43
+ # TTY::Prompt against a StringIO.
44
+ def self.invoke(ctx, scope, ui: nil, probe: nil)
45
+ ui ||= Rubik::Connect::PromptUI.new(input: ctx.input, output: ctx.out, theme: ctx.theme)
46
+ Rubik::Connect::Wizard.new(config: ctx.config, ui: ui, io: ctx.out, scope: scope,
47
+ refresh: -> { ctx.refresh_llm_registry! }, probe: probe).run
48
+ end
49
+ end
50
+ end
51
+ end
52
+ end
@@ -7,6 +7,7 @@ require_relative "commands/session"
7
7
  require_relative "commands/workspace"
8
8
  require_relative "commands/lsp"
9
9
  require_relative "commands/agent"
10
+ require_relative "commands/connect"
10
11
  require_relative "commands/plugins"
11
12
  require_relative "commands/mcp"
12
13
  require_relative "commands/skills"
@@ -26,6 +27,7 @@ module Rubik
26
27
  Workspace,
27
28
  Lsp,
28
29
  Agent,
30
+ Connect,
29
31
  Plugins,
30
32
  Mcp,
31
33
  Skills,
@@ -162,6 +162,10 @@ module Rubik
162
162
  # an unbound read would mask the in-flight exception with a
163
163
  # NameError, breaking the "cleanup must never mask" contract.
164
164
  interrupted = false
165
+ # Resume bayatlaşması: kullanıcı yeni bir görev yazdıysa duraklatılmış
166
+ # turn teklifi geçersizdir (otonom notice turn'i stash'i ezmez —
167
+ # kullanıcının "devam et"i bir notice turn'ine kurban edilmesin).
168
+ @resumable_turn = nil unless @autonomous_turn
165
169
  task = start_free_text_turn!(text)
166
170
  renderer = md_stream = orchestrator = nil
167
171
  routed = route_free_text!(text)
@@ -292,7 +296,22 @@ module Rubik
292
296
  def run_free_text_loop(orchestrator, text)
293
297
  @active_loop = orchestrator
294
298
  res = orchestrator.run(text, conversation_history: @conversation_history)
299
+ drive_budget_continuations!(orchestrator, res)
300
+ end
295
301
 
302
+ # Resume koşusu: ölü turn'in Loop örneği @active_loop olarak
303
+ # yayınlanır (reentrancy guard, run_free_text_loop ile aynı sözleşme)
304
+ # ve taze display kanalı Loop#resume_turn! devam sözleşmesine
305
+ # geçirilir. Sayaçlar ve @history bilinçli korunur.
306
+ def resume_free_text_loop(orchestrator, renderer, md_stream)
307
+ @active_loop = orchestrator
308
+ res = orchestrator.resume_turn!(reason: RESUME_REASON, on_step: turn_step_handler(renderer, md_stream))
309
+ drive_budget_continuations!(orchestrator, res)
310
+ end
311
+
312
+ # Budget-continue döngüsü (run_free_text_loop'tan çıkarıldı): taze
313
+ # turn ile resume koşusu aynı devam-sorusu kalıbını paylaşır.
314
+ def drive_budget_continuations!(orchestrator, res)
296
315
  while !res[:ok] && res[:reason] == :budget_exhausted && Rubik::Storage::Layout.config_get(@config, "agent.ask_continue_on_limit", true)
297
316
  @output.puts "\n⚠️ [Rubik::Agent] #{res[:error]}"
298
317
  ans = ask_yes_no(" [Rubik::Agent] +20 adım ile devam edilsin mi?", default: "n")
@@ -313,10 +332,7 @@ module Rubik
313
332
  # conversation_history'ye kopyala — böylece continue'da model turn sırasındaki
314
333
  # bağlamı görür ve "sıfırdan keşfe" başlamaz. res[:loop_instance].history,
315
334
  # turn_result'ın döndürdüğü Loop örneğinin @history'sidir.
316
- merge_turn_tool_history!(
317
- res[:loop_instance]&.history,
318
- max_entries: Rubik::Storage::Layout.config_get(@config, "context.merge_turn_tool_max_entries", 20).to_i
319
- )
335
+ merge_unseen_turn_tool_history!(res[:loop_instance])
320
336
 
321
337
  if res[:ok]
322
338
  record_turn_outcome!(text, res[:output].to_s, tokens: res[:tokens], streamed: res[:streamed] == true)
@@ -345,6 +361,125 @@ module Rubik
345
361
  end
346
362
  end
347
363
 
364
+ # Turn-exit tool-history merge for non-settle exits (LLM error,
365
+ # unexpected error, ^C). Same policy as settle_free_text_result!'s
366
+ # merge: the loop's in-turn @history carries the tool steps the next
367
+ # turn needs, and merge_turn_tool_history!'s own contract is
368
+ # path-independent ("hata veya başarı fark etmez"). Without this the
369
+ # failure handlers persist only the 15-line chronicle, and "devam et"
370
+ # after a mid-run LLM error makes the model re-discover terrain from
371
+ # a summary instead of the actual last tool results (2026-11-16
372
+ # field report: [41/50] Net::ReadTimeout → re-discovery turn).
373
+ # Ordering contract: call AFTER record_failed_turn! — the outcome
374
+ # text (user + failure pair) must lead the window, otherwise trim's
375
+ # leading-role guard evicts the freshly merged tool messages on a
376
+ # fresh/empty conversation window (first-turn failure).
377
+ def merge_failed_turn_tool_history!(orchestrator)
378
+ return unless orchestrator.respond_to?(:history)
379
+
380
+ merge_unseen_turn_tool_history!(orchestrator)
381
+ end
382
+
383
+ def merge_unseen_turn_tool_history!(loop_instance)
384
+ return unless loop_instance.respond_to?(:history)
385
+
386
+ history = loop_instance.history
387
+ return if history.nil?
388
+
389
+ @merged_history_cursors ||= ObjectSpace::WeakMap.new
390
+ cursor = @merged_history_cursors[loop_instance] || 0
391
+ cursor = 0 if cursor > history.length
392
+ unseen = history[cursor..]
393
+ @merged_history_cursors[loop_instance] = history.length
394
+ return if unseen.nil? || unseen.empty?
395
+
396
+ merge_turn_tool_history!(
397
+ unseen,
398
+ max_entries: Rubik::Storage::Layout.config_get(@config, "context.merge_turn_tool_max_entries", 20).to_i
399
+ )
400
+ end
401
+
402
+ # ── Hata-sonrası turn resume (2026-11-16) ──────────────────────────
403
+ # LLM hatasıyla ölen serbest-metin turn'i, taze Loop kurulMADAN aynı
404
+ # Loop örneği üzerinden sürdürülebilir: Loop örneği @resumable_turn'te
405
+ # saklanır, kullanıcı resume-niyetinde bir satır yazdığında
406
+ # Loop#resume_turn! devam sözleşmesi (continue_loop/resume! ile aynı
407
+ # execute_steps yolu) işletilir — aynı @history, aynı adım bütçesi
408
+ # (kullanıcının !steps extend'i dahil). Amaç-eşleşmesi BİREBİRDİR:
409
+ # substring eşleşmesi yeni bir görevi yanlışlıkla resume sanabilir.
410
+ RESUME_INTENTS = ["devam et", "devam", "continue", "sürdür"].freeze
411
+ RESUME_PROMPT = "devam et"
412
+ RESUME_REASON = "llm_error_recovery"
413
+
414
+ def resumable_turn? = !!@resumable_turn
415
+
416
+ # Trailing punctuation allowed after a resume phrase ("devam!…"). Kept as
417
+ # a plain string used with #include? — a /[…]+\z/ regex strip on
418
+ # uncontrolled input is a polynomial-ReDoS hazard (CodeQL rb/polynomial-redos).
419
+ RESUME_TRAILING_PUNCT = ".!?…"
420
+
421
+ def resume_intent?(raw)
422
+ return false unless @resumable_turn
423
+
424
+ s = raw.to_s.strip.downcase
425
+ idx = s.length - 1
426
+ idx -= 1 while idx >= 0 && RESUME_TRAILING_PUNCT.include?(s[idx])
427
+ # s[0, idx + 1] — NOT s[0..idx]: with idx == -1 a range slice returns
428
+ # the WHOLE string ("!!!"[0..-1] == "!!!"); length-form never does.
429
+ RESUME_INTENTS.include?(s[0, idx + 1])
430
+ end
431
+
432
+ # Most-recent-wins: yeni bir turn hatayla ölürse önceki resumable'ın
433
+ # yerine geçer. execute_free_text, otonom notice turn'leri hariç,
434
+ # stash'i temizler (kullanıcı yeni görev seçtiyse resume teklifi
435
+ # bayatlaşır); bir turn başarısız olduktan sonra tekrar dolar.
436
+ def stash_resumable_turn!(orchestrator)
437
+ return false unless orchestrator.respond_to?(:resume_turn!) && orchestrator.respond_to?(:history)
438
+
439
+ @resumable_turn = { loop: orchestrator }
440
+ true
441
+ end
442
+
443
+ def stash_and_announce_resume!(orchestrator)
444
+ return unless stash_resumable_turn!(orchestrator)
445
+
446
+ @output.puts "[Rubik] Turn duraklatıldı (adım #{orchestrator.step_count}/#{orchestrator.max_steps}). " \
447
+ "'devam et' yazarsan aynı bağlam ve adım bütçesiyle sürer; başka bir şey yazarsan yeni görev olarak koşar."
448
+ end
449
+
450
+ # Duraklatılmış turn'in yeniden koşusu: taze turn yaşam döngüsünü
451
+ # (arming → display → settle → rescue merdiveni → ensure teardown)
452
+ # resume sözleşmesiyle birleştirir. Kullanıcının yazdığı satır
453
+ # recorder'a ve konuşma hafızasına "devam et" olarak düşer — dürüst
454
+ # provenance; orijinal görev metni Loop'un kendi @history'sinde
455
+ # yaşamaya devam eder ve modele tekrar gönderilmez.
456
+ def execute_resumed_turn!
457
+ rt = @resumable_turn
458
+ @resumable_turn = nil
459
+ return false unless rt
460
+
461
+ interrupted = false
462
+ orchestrator = rt[:loop]
463
+ task = start_free_text_turn!(RESUME_PROMPT)
464
+ renderer = md_stream = nil
465
+ begin
466
+ theme = self.theme
467
+ renderer, md_stream, md_enabled = build_turn_display(theme, orchestrator.max_steps)
468
+ res = resume_free_text_loop(orchestrator, renderer, md_stream)
469
+ settle_free_text_result!(RESUME_PROMPT, res, orchestrator: orchestrator, theme: theme, md_enabled: md_enabled)
470
+ rescue Interrupt
471
+ interrupted = true
472
+ handle_interrupted_free_text!(RESUME_PROMPT, task, orchestrator)
473
+ rescue Rubik::LLM::ClientError => e
474
+ handle_llm_client_error!(RESUME_PROMPT, e, orchestrator)
475
+ rescue StandardError => e
476
+ handle_unexpected_error!(RESUME_PROMPT, e, orchestrator)
477
+ ensure
478
+ teardown_free_text_turn!(interrupted, orchestrator, renderer, md_stream)
479
+ end
480
+ true
481
+ end
482
+
348
483
  # Interrupt rescue body: the user cancelled — queued wake debts settle
349
484
  # here. Each queued notice already lives in @conversation_history (idle
350
485
  # path injects at route time), so draining loses nothing the model
@@ -365,6 +500,7 @@ module Rubik
365
500
  "reason" => "Interrupted by user (^C)")
366
501
  @output.puts "\n⚠️ [Rubik::Agent] Görev kullanıcı tarafından iptal edildi (^C)."
367
502
  record_failed_turn!(text, "cancelled", "Interrupted by user (^C)", orchestrator)
503
+ merge_failed_turn_tool_history!(orchestrator)
368
504
  end
369
505
 
370
506
  # LLM::ClientError rescue body. e.message may carry binary bytes (raw
@@ -376,6 +512,8 @@ module Rubik
376
512
  message = Rubik::Platform.safe_utf8(error.message)
377
513
  @output.puts "[Rubik::LLM Hatası] #{message}"
378
514
  record_failed_turn!(text, "failed", message, orchestrator)
515
+ merge_failed_turn_tool_history!(orchestrator)
516
+ stash_and_announce_resume!(orchestrator) unless @autonomous_turn
379
517
  end
380
518
 
381
519
  # StandardError rescue body: same binary-byte sanitization as the LLM
@@ -384,6 +522,7 @@ module Rubik
384
522
  message = Rubik::Platform.safe_utf8(error.message)
385
523
  @output.puts "[Hata] #{error.class}: #{message}"
386
524
  record_failed_turn!(text, "failed", "#{error.class}: #{message}", orchestrator)
525
+ merge_failed_turn_tool_history!(orchestrator)
387
526
  end
388
527
 
389
528
  # Ensure-phase teardown. Cleanup must never mask the in-flight exception
@@ -26,6 +26,7 @@ module Rubik
26
26
  heredoc_delimiter = nil
27
27
  last_line_at = nil
28
28
  print_banner
29
+ maybe_offer_connect_wizard! if respond_to?(:maybe_offer_connect_wizard!)
29
30
  Rubik::REPL::InterruptHandler.with_handler do
30
31
  while @running
31
32
  result = read_and_process_line(multiline_buffer, heredoc_delimiter, last_line_at: last_line_at)
@@ -4,6 +4,8 @@ require_relative "../events"
4
4
  require_relative "../log"
5
5
  require_relative "../platform"
6
6
  require_relative "../storage/layout"
7
+ require_relative "../ui/capability"
8
+ require_relative "../connect"
7
9
  require_relative "../orchestrator/subagent/notices"
8
10
  require_relative "../prompt/conversation_rows"
9
11
  require_relative "pending_notice_queue"
@@ -133,6 +135,43 @@ module Rubik
133
135
  resync_llm_route!
134
136
  end
135
137
 
138
+ # First-run onboarding: after the banner shows "model yapılandırılmamış",
139
+ # offer the connect wizard once when boot could not resolve an LLM
140
+ # client. Opt-in ask (default no — Confirmations#ask_yes_no collapses
141
+ # to the default off live TTYs, so scripted boots are untouched),
142
+ # knob-gated (connect.first_run_offer), once per process, never
143
+ # raises — the same boot-path honesty as sync_default_llm_route.
144
+ def maybe_offer_connect_wizard!
145
+ return if @connect_offer_shown
146
+
147
+ @connect_offer_shown = true
148
+ return unless @config && @output && @input
149
+ return unless respond_to?(:ask_yes_no)
150
+ return unless Rubik::UI::Capability.interactive?(input: @input, output: @output)
151
+ return unless Rubik::Storage::Layout.config_get(@config, "connect.first_run_offer", true)
152
+ return unless llm_client_pending?
153
+
154
+ answer = ask_yes_no("Hiç model sağlayıcısı yapılandırılmamış görünüyor. Bağlantı sihirbazı çalıştırılsın mı? / " \
155
+ "No LLM provider is configured yet. Run the connect wizard?", default: "n")
156
+ return unless ["y", "yes", "evet"].include?(answer.to_s.downcase)
157
+
158
+ ui = Rubik::Connect::PromptUI.new(input: @input,
159
+ output: Rubik::UI::Capability.unwrap_tee(@output) || @output,
160
+ theme: @ui_theme)
161
+ Rubik::Connect::Wizard.new(config: @config, ui: ui, io: @output, scope: :global,
162
+ refresh: -> { refresh_llm_registry! }).run
163
+ rescue StandardError => e
164
+ debug_warn("Connect wizard offer failed: #{e.class}: #{e.message}")
165
+ end
166
+
167
+ # True when boot's default route failed to satisfy the llm_client
168
+ # coeffect — the honest "nothing usable is configured" signal, so a
169
+ # locally-running Ollama user is never offered the wizard.
170
+ def llm_client_pending?
171
+ context = @runtime_manager&.context
172
+ context.respond_to?(:get) ? context.get(:llm_client).nil? : false
173
+ end
174
+
136
175
  # Live LLM re-route (reactive config wiring, !model/!provider switches):
137
176
  # re-open sticky routing so the next free-text turn re-resolves with the
138
177
  # new model (Plan 61 D-7), then re-provide the default llm_client
@@ -201,7 +201,15 @@ module Rubik
201
201
  when :command
202
202
  execute_command(parsed)
203
203
  when :prompt
204
- execute_free_text(parsed.raw)
204
+ # Hata-sonrası turn resume: duraklatılmış bir turn varsa ve satır
205
+ # birebir resume niyeti taşıyorsa taze Loop kurulmaz — aynı Loop
206
+ # örneği, aynı @history ve adım bütçesiyle sürer (stash yoksa
207
+ # "devam et" sıradan bir serbest-metin görevi olarak koşar).
208
+ if resume_intent?(parsed.raw)
209
+ execute_resumed_turn!
210
+ else
211
+ execute_free_text(parsed.raw)
212
+ end
205
213
  end
206
214
 
207
215
  check_dirty_buffer_reminder unless @replaying
@@ -73,6 +73,7 @@ module Rubik
73
73
  end
74
74
 
75
75
  def activate!(context)
76
+ return false if @state == :disposed
76
77
  return true if @state == :active
77
78
  return false unless ready_to_activate?(context)
78
79