rubik 0.11.0 → 0.12.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 (41) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +57 -1
  3. data/lib/rubik/buffer/manager.rb +3 -3
  4. data/lib/rubik/config/deep_ops.rb +3 -1
  5. data/lib/rubik/config/defaults.rb +8 -8
  6. data/lib/rubik/config/schema.rb +7 -0
  7. data/lib/rubik/config/secret_policy.rb +14 -5
  8. data/lib/rubik/config.rb +1 -1
  9. data/lib/rubik/llm/anthropic.rb +2 -1
  10. data/lib/rubik/llm/client.rb +22 -6
  11. data/lib/rubik/llm/formatter.rb +4 -1
  12. data/lib/rubik/llm/ollama.rb +2 -1
  13. data/lib/rubik/llm/openai_compatible.rb +2 -1
  14. data/lib/rubik/llm/router.rb +6 -1
  15. data/lib/rubik/llm/sse_parser.rb +17 -14
  16. data/lib/rubik/mcp/manager.rb +14 -1
  17. data/lib/rubik/mcp/proxy_tool.rb +2 -2
  18. data/lib/rubik/mcp/transport/stdio.rb +3 -2
  19. data/lib/rubik/orchestrator/goal_state.rb +6 -2
  20. data/lib/rubik/orchestrator/loop.rb +30 -6
  21. data/lib/rubik/orchestrator/provider_resolver.rb +12 -0
  22. data/lib/rubik/orchestrator/subagent/step_runner.rb +7 -0
  23. data/lib/rubik/platform/filesystem.rb +2 -2
  24. data/lib/rubik/repair/loop.rb +1 -1
  25. data/lib/rubik/repl/input_execution.rb +143 -4
  26. data/lib/rubik/repl/shell.rb +9 -1
  27. data/lib/rubik/runtime/fiber.rb +1 -0
  28. data/lib/rubik/runtime/manager.rb +4 -1
  29. data/lib/rubik/runtime/task_manager.rb +3 -3
  30. data/lib/rubik/sandbox/driver/base.rb +7 -0
  31. data/lib/rubik/sandbox/driver/docker.rb +1 -4
  32. data/lib/rubik/sandbox/driver/podman.rb +1 -0
  33. data/lib/rubik/sandbox/runner.rb +1 -1
  34. data/lib/rubik/security/classifier/classifier.rb +2 -0
  35. data/lib/rubik/storage/store.rb +4 -1
  36. data/lib/rubik/tools/registry.rb +36 -16
  37. data/lib/rubik/ui/capability.rb +6 -4
  38. data/lib/rubik/ui/markdown_stream.rb +1 -0
  39. data/lib/rubik/ui/renderer.rb +4 -2
  40. data/lib/rubik/version.rb +1 -1
  41. metadata +1 -1
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: c51c73960cae7dc1fc2f89745c3261cc1d4693bbde7c449175f5c16b8f076bbd
4
- data.tar.gz: 7f570e596aafd7ad9b82d634ef9a38d739e027eb2a7c50b613c2b97be5850c6b
3
+ metadata.gz: f668c26bd4967d506b511a23d21f1a9afe91cc0c94b6d007b39e4dd1d4102e7e
4
+ data.tar.gz: b4d12df2cc31b33e86a97c5a1a2f050f42bbc612169eb54d36a96d238f9b5445
5
5
  SHA512:
6
- metadata.gz: ab509129d3f7f20498535c0b51f48e1a902af9484108eb0c12f3f8c13cc5010e1a359f6474aca6742dd09a16e4dded9645ab41b844afbea5eb01b41e7a09725e
7
- data.tar.gz: 40430100af1ca2a9049ace43864ea82d3dcfad72e005ac1698fe71c5b0a7585e56b32f59a22aea1e7339ea689dd569e346f2f540273ac633e5cfd409c9c1386c
6
+ metadata.gz: 4072b8c92a9f9990227c1b72996a48942fd1008a849bf9e6d6ff74c80f1448dbd10d5409158e85e1c7c5ae54463f69b0b9a68b07a542a87cb51a837e8bee4751
7
+ data.tar.gz: 5a9679b4f592d999e9602af4758327347f7bf5a84eee8e0b70bb5591830eab73a65dfcc1cf7bb78ae171b2e4b32bea9ef52c8ce6f704d9806db9d440e5cef9fc
data/CHANGELOG.md CHANGED
@@ -6,6 +6,61 @@ commits, 2026-08-23 → 2026-10-09, see `git log`).
6
6
 
7
7
  The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
8
8
 
9
+ ## [0.12.0] - 2026-11-17
10
+
11
+ The retry-and-resume minor: the LLM transport's hardcoded rate-limit and 5xx
12
+ retry budgets become typed, operator-tunable `llm.*` knobs threaded end to
13
+ end into both agent loops, and an error-interrupted REPL turn keeps its tool
14
+ history and resumes on the same Loop instead of forcing the model to
15
+ re-discover terrain from a summary — while a robustness round protects the
16
+ storage config from redaction, rolls back failed persists, hardens the
17
+ sandbox drivers against catastrophic fallbacks, scrubs the MCP server
18
+ environment, sanitizes terminal-escape output, and fixes goal token
19
+ double-counting.
20
+
21
+ ### Added
22
+
23
+ - **Operator-tunable LLM retry budgets (`llm.max_retries`, `max_429_retries`,
24
+ `backoff_base`, `max_wall_clock`, `rate_limit_max_delay`):** the transport
25
+ layer's hardcoded rate-limit and transient-5xx constants become typed
26
+ defaults tunable globally or per provider (English and Turkish
27
+ configuration guides updated), threaded through the transport and both
28
+ agent loops (root loop and subagent step runner) via a helper that passes
29
+ only explicitly-set values so existing callers keep their built-in
30
+ defaults; the Retry-After delay clamp is configurable end to end with the
31
+ old ceiling preserved as the fallback.
32
+
33
+ ### Changed
34
+
35
+ - **Failed free-text turns merge their tool history into conversation memory
36
+ (#511):** a mid-run LLM error no longer drops the in-turn tool messages —
37
+ the path-independent merge contract is wired into all three failure rescue
38
+ bodies (LLM error, unexpected error, ^C) with the outcome text leading the
39
+ window.
40
+
41
+ ### Fixed
42
+
43
+ - **An error-interrupted free-text turn resumes on the same Loop (#511):** the
44
+ REPL stashes the surviving Loop and an exact-match resume intent
45
+ ("devam et"/"continue"/…) continues from the interrupted step counter with
46
+ a `<turn_resumed>` marker instead of spawning a fresh Loop; resume-intent
47
+ parsing is linear-time (CodeQL polynomial ReDoS) with a length-form slice
48
+ guard.
49
+ - **Fiber retry resurrection, goal token double-count, and resume
50
+ history/stash (#528):** the runtime retry path can no longer resurrect a
51
+ disposed fiber, goal tokens are counted once, and loop history cursors use
52
+ `ObjectSpace::WeakMap` so completed Loops are not retained.
53
+ - **Terminal escapes sanitized, conflict FrozenError, SSE UTF-8, router enum,
54
+ fence tags (#530):** a robustness sweep across ui/buffer/llm/repair.
55
+ - **MCP proxy collisions, server restart on re-add, env scrubbing, and
56
+ registry alias ownership (#527).**
57
+ - **Storage config protected from redaction, failed persists rolled back,
58
+ digit hash lookup and atomic_write fixed (#529):** session-only semantics
59
+ are preserved when a disk persist fails.
60
+ - **Catastrophic fallback regex enforced and sandbox drivers hardened
61
+ (#526):** `/$x`-style patterns are classified as system paths and
62
+ `resolved_path_under?` is reused.
63
+
9
64
  ## [0.11.0] - 2026-11-16
10
65
 
11
66
  The schema-grammar minor: the goal-ledger stops teaching its schema through
@@ -1729,7 +1784,8 @@ installation section.
1729
1784
  - Context: serialized index mutations, snapshot-outside-lock reconcile,
1730
1785
  streaming-first truncation.
1731
1786
 
1732
- [Unreleased]: https://github.com/ozgurulukir/rubik/compare/v0.11.0...HEAD
1787
+ [Unreleased]: https://github.com/ozgurulukir/rubik/compare/v0.12.0...HEAD
1788
+ [0.12.0]: https://github.com/ozgurulukir/rubik/compare/v0.11.0...v0.12.0
1733
1789
  [0.11.0]: https://github.com/ozgurulukir/rubik/compare/v0.10.0...v0.11.0
1734
1790
  [0.10.0]: https://github.com/ozgurulukir/rubik/compare/v0.9.1...v0.10.0
1735
1791
  [0.9.1]: https://github.com/ozgurulukir/rubik/compare/v0.9.0...v0.9.1
@@ -183,7 +183,7 @@ module Rubik
183
183
  @buffer.delete(rel_path)
184
184
  @dirty_files.delete(rel_path)
185
185
  @original_hashes.delete(rel_path)
186
- @last_conflicts.delete(rel_path)
186
+ @last_conflicts = @last_conflicts.reject { |c| c == rel_path }.freeze
187
187
  end
188
188
 
189
189
  if from_disk
@@ -210,7 +210,7 @@ module Rubik
210
210
  @buffer.delete(rel_path)
211
211
  @dirty_files.delete(rel_path)
212
212
  @original_hashes.delete(rel_path)
213
- @last_conflicts.delete(rel_path)
213
+ @last_conflicts = @last_conflicts.reject { |c| c == rel_path }.freeze
214
214
  @event_bus&.emit(:buffer_discarded, path: rel_path)
215
215
  rel_path
216
216
  end
@@ -286,7 +286,7 @@ module Rubik
286
286
  rel = path.byteslice((root_size + 1)..-1)
287
287
  rel = rel.tr("\\", "/") if File::ALT_SEPARATOR
288
288
 
289
- if rel.start_with?(".git")
289
+ if rel == ".git" || rel.start_with?(".git/")
290
290
  Find.prune if File.directory?(path)
291
291
  next
292
292
  end
@@ -7,7 +7,9 @@ module Rubik
7
7
  "security", "sandbox", "plugins", "mcp", "lsp", "project", "test", "linter", "adapter",
8
8
  # Provider specs carry credentials and endpoints; an untrusted
9
9
  # project must not be able to inject either.
10
- "providers"
10
+ "providers",
11
+ # Storage root/project slug must not be redirected by an untrusted workspace.
12
+ "storage"
11
13
  ].freeze
12
14
 
13
15
  private
@@ -5,19 +5,19 @@ require_relative "../platform"
5
5
  module Rubik
6
6
  class Config
7
7
  module Defaults
8
+ # llm.* transport-resilience fallbacks, reused by both orchestrator seams.
9
+ LLM_RETRY_DEFAULTS = { "max_retries" => 2, "max_429_retries" => 5, "backoff_base" => 0.2,
10
+ "max_wall_clock" => 120, "rate_limit_max_delay" => 60 }.freeze
11
+
8
12
  DEFAULT_CONFIG = {
9
13
  "llm" => {
10
- "stream" => true,
11
- "stream_timeout" => 120,
12
- "open_timeout" => 15,
13
- "default_max_output_tokens" => 4096,
14
- "capture_reasoning" => true,
15
- "auto_continue_on_length" => true,
16
- "max_auto_continues" => 3,
14
+ "stream" => true, "stream_timeout" => 120, "open_timeout" => 15, "default_max_output_tokens" => 4096,
15
+ "capture_reasoning" => true, "auto_continue_on_length" => true, "max_auto_continues" => 3,
17
16
  # Plan 90 bridge (loop.rb): nil = not sent; non-nil reasoning_effort also flips reasoning_model?.
18
17
  "thinking_budget_ratio" => nil, # Anthropic thinking budget share (0.0-0.8) -> opts[:thinking_budget_ratio]
19
18
  "reasoning_effort" => nil, # OpenAI reasoning effort "low"|"medium"|"high" -> opts[:reasoning_effort]
20
- "headers" => {}
19
+ "headers" => {},
20
+ **LLM_RETRY_DEFAULTS
21
21
  },
22
22
  "model" => { "provider" => "ollama", "name" => "qwen2.5-coder:7b", "endpoint" => "http://localhost:11434" },
23
23
  "models" => {
@@ -14,6 +14,13 @@ module Rubik
14
14
  "llm.capture_reasoning" => { type: :boolean },
15
15
  "llm.auto_continue_on_length" => { type: :boolean },
16
16
  "llm.max_auto_continues" => { type: :integer, min: 0 },
17
+ # HTTP transport retry budgets (llm/client.rb post_json). 0 disables
18
+ # a budget; backoff_base is seconds; max_wall_clock bounds all retries.
19
+ "llm.max_retries" => { type: :integer, min: 0 },
20
+ "llm.max_429_retries" => { type: :integer, min: 0 },
21
+ "llm.backoff_base" => { type: :float, min: 0.0 },
22
+ "llm.max_wall_clock" => { type: :integer, min: 0 },
23
+ "llm.rate_limit_max_delay" => { type: :integer, min: 0 },
17
24
  "llm.thinking_budget_ratio" => { type: :float, min: 0.0, max: 0.8, nullable: true },
18
25
  "llm.reasoning_effort" => { type: :enum, allowed: ["low", "medium", "high"], nullable: true },
19
26
  "agent.max_steps" => { type: :integer, min: 1 },
@@ -123,11 +123,20 @@ module Rubik
123
123
  # of an api_key path also drops its stored secret(s) — both scopes'
124
124
  # names, so neither keyring entry outlives its reference. Best-effort
125
125
  # — never masks res.
126
- def cleanup_stored_secret(key, res, persist)
127
- return unless secret_key?(key) && res[:ok] && persisting?(persist)
128
-
129
- Rubik::Security::SecretStore.delete(key.to_s)
130
- Rubik::Security::SecretStore.delete("#{key}.project")
126
+ def cleanup_stored_secret(key, res, persist, old_val: nil)
127
+ return unless res[:ok] && persisting?(persist)
128
+
129
+ keys_to_delete = if secret_key?(key)
130
+ [key.to_s]
131
+ elsif old_val.is_a?(Hash)
132
+ collect_secret_leaves(key, old_val).map(&:first)
133
+ else
134
+ []
135
+ end
136
+ keys_to_delete.each do |secret_path|
137
+ Rubik::Security::SecretStore.delete(secret_path)
138
+ Rubik::Security::SecretStore.delete("#{secret_path}.project")
139
+ end
131
140
  rescue Rubik::Security::SecretStore::Error
132
141
  nil
133
142
  end
data/lib/rubik/config.rb CHANGED
@@ -167,7 +167,7 @@ module Rubik
167
167
  notify_change(key, new_val, old_val)
168
168
  @event_bus&.emit(:config_deleted, key: key.to_s, old_val: old_val)
169
169
  end
170
- cleanup_stored_secret(key, res, persist)
170
+ cleanup_stored_secret(key, res, persist, old_val: old_val)
171
171
  res
172
172
  end
173
173
  end
@@ -99,7 +99,8 @@ module Rubik
99
99
  payload: payload,
100
100
  timeout: timeout,
101
101
  open_timeout: open_timeout,
102
- on_retry: opts[:on_retry]
102
+ on_retry: opts[:on_retry],
103
+ **HTTPClient.retry_opts_from(opts)
103
104
  )
104
105
 
105
106
  content_blocks = res_json["content"] || []
@@ -66,6 +66,21 @@ module Rubik
66
66
  # interactive agent turn indefinitely.
67
67
  RATE_LIMIT_MAX_DELAY_S = 60
68
68
 
69
+ # Retry knobs that may be supplied per call (resolved from llm.* config
70
+ # by the orchestrator seams) and forwarded to post_json. Only keys that
71
+ # are explicitly present are forwarded: passing nil would break the
72
+ # `retries < max_retries` comparisons in the retry loop.
73
+ RETRY_OPTION_KEYS = [
74
+ :max_retries, :max_429_retries, :backoff_base, :max_wall_clock, :rate_limit_max_delay
75
+ ].freeze
76
+
77
+ def self.retry_opts_from(opts)
78
+ RETRY_OPTION_KEYS.each_with_object({}) do |key, out|
79
+ value = opts[key]
80
+ out[key] = value unless value.nil?
81
+ end
82
+ end
83
+
69
84
  # Read a response header defensively: test doubles and exotic response
70
85
  # objects may not implement the Net::HTTPHeader interface.
71
86
  def self.header_value(res, name)
@@ -93,14 +108,14 @@ module Rubik
93
108
  # when present (honored exactly — the server knows its own window);
94
109
  # otherwise exponential backoff with ±20% jitter to de-synchronize
95
110
  # concurrent clients hammering the same endpoint. Both capped.
96
- def self.retry_delay_after(res, retries, backoff_base)
111
+ def self.retry_delay_after(res, retries, backoff_base, max_delay: RATE_LIMIT_MAX_DELAY_S)
97
112
  hint = parse_retry_after(header_value(res, "Retry-After"))
98
113
  delay = hint
99
114
  unless delay
100
115
  delay = backoff_base * (2**(retries - 1))
101
116
  delay *= (0.8 + (0.4 * rand))
102
117
  end
103
- delay.clamp(0, RATE_LIMIT_MAX_DELAY_S)
118
+ delay.clamp(0, max_delay)
104
119
  end
105
120
 
106
121
  # `retries` is nil on paths that never entered the retry loop (streaming)
@@ -151,10 +166,11 @@ module Rubik
151
166
  # a typed error when exhausted so callers can report "provider
152
167
  # throttled" distinctly. The generic 5xx budget is untouched, so
153
168
  # one 429 burst cannot exhaust the transport-failure budget.
154
- def self.handle_429_retry(res, rate_limit_retries:, max_429_retries:, start_time:, backoff_base:, max_wall_clock:, on_retry:)
169
+ def self.handle_429_retry(res, rate_limit_retries:, max_429_retries:, start_time:, backoff_base:, max_wall_clock:, on_retry:,
170
+ rate_limit_max_delay: RATE_LIMIT_MAX_DELAY_S)
155
171
  if rate_limit_retries < max_429_retries
156
172
  elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - start_time
157
- delay = retry_delay_after(res, rate_limit_retries + 1, backoff_base)
173
+ delay = retry_delay_after(res, rate_limit_retries + 1, backoff_base, max_delay: rate_limit_max_delay)
158
174
  if elapsed + delay <= max_wall_clock
159
175
  rate_limit_retries += 1
160
176
  on_retry&.call(rate_limit_retries, max_429_retries, "HTTP 429")
@@ -202,7 +218,7 @@ module Rubik
202
218
 
203
219
  def self.post_json(url_str, headers: {}, payload: {}, timeout: 30, open_timeout: 10,
204
220
  max_retries: 2, max_429_retries: 5, backoff_base: 0.2, max_wall_clock: 120,
205
- on_retry: nil, http_factory: nil)
221
+ rate_limit_max_delay: RATE_LIMIT_MAX_DELAY_S, on_retry: nil, http_factory: nil)
206
222
  uri = parse_and_validate_uri(url_str)
207
223
  start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
208
224
  retries = 0
@@ -216,7 +232,7 @@ module Rubik
216
232
  rate_limit_retries = handle_429_retry(
217
233
  res, rate_limit_retries: rate_limit_retries, max_429_retries: max_429_retries,
218
234
  start_time: start_time, backoff_base: backoff_base, max_wall_clock: max_wall_clock,
219
- on_retry: on_retry
235
+ rate_limit_max_delay: rate_limit_max_delay, on_retry: on_retry
220
236
  )
221
237
  next
222
238
  end
@@ -326,7 +326,10 @@ module Rubik
326
326
  chunk = Chunk.new(usage: usage, raw: parsed)
327
327
  when "message_stop"
328
328
  chunk = Chunk.new(done: true, raw: parsed)
329
- when "message_start", "content_block_start", "content_block_stop"
329
+ when "message_start"
330
+ usage = parsed.dig("message", "usage")
331
+ chunk = Chunk.new(usage: usage, raw: parsed)
332
+ when "content_block_start", "content_block_stop"
330
333
  chunk = Chunk.new(raw: parsed)
331
334
  end
332
335
 
@@ -47,7 +47,8 @@ module Rubik
47
47
  payload: payload,
48
48
  timeout: timeout,
49
49
  open_timeout: open_timeout,
50
- on_retry: opts[:on_retry]
50
+ on_retry: opts[:on_retry],
51
+ **HTTPClient.retry_opts_from(opts)
51
52
  )
52
53
 
53
54
  msg_content = res_json.dig("message", "content") || ""
@@ -68,7 +68,8 @@ module Rubik
68
68
  payload: payload,
69
69
  timeout: timeout,
70
70
  open_timeout: open_timeout,
71
- on_retry: opts[:on_retry]
71
+ on_retry: opts[:on_retry],
72
+ **HTTPClient.retry_opts_from(opts)
72
73
  )
73
74
 
74
75
  build_response(res_json, messages)
@@ -45,7 +45,12 @@ module Rubik
45
45
  # explicit `provider:` opt) and delegates to its `#stream_chat`.
46
46
  # Yields Chunks. Without a block, returns an Enumerator.
47
47
  def stream_chat(messages, task_type: :auto, prompt: "", provider: nil, **opts, &block)
48
- chosen_route = provider ? { provider: @registry.get(provider) } : route(task_type: task_type, prompt: prompt)
48
+ chosen_route = if provider
49
+ resolved = provider.respond_to?(:stream_chat) ? provider : @registry.get(provider)
50
+ { provider: resolved }
51
+ else
52
+ route(task_type: task_type, prompt: prompt)
53
+ end
49
54
  chosen = chosen_route[:provider]
50
55
  raise ClientError, "No provider available for streaming" unless chosen
51
56
 
@@ -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
@@ -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
@@ -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
 
@@ -185,6 +185,8 @@ module Rubik
185
185
  return unless deferred
186
186
 
187
187
  @retry_gate.attempt(deferred) do |fiber|
188
+ next unless @fibers[fiber.name].equal?(fiber) && fiber.state != :disposed
189
+
188
190
  with_activation_marker(fiber) { fiber.activate!(@context) }
189
191
  end
190
192
  end
@@ -241,7 +243,8 @@ module Rubik
241
243
  # fibers react to canonical re-provides instead of holding stale
242
244
  # service instances.
243
245
  def fiber_depends_on_service?(fiber, changed_key)
244
- fiber.inject.any? { |dep| dep == changed_key || Rubik::Coeffects.canonical(dep) == changed_key }
246
+ canonical_changed = Rubik::Coeffects.canonical(changed_key)
247
+ fiber.inject.any? { |dep| dep == changed_key || Rubik::Coeffects.canonical(dep) == canonical_changed }
245
248
  end
246
249
  end
247
250
  end
@@ -83,18 +83,18 @@ module Rubik
83
83
  attr_reader :guard, :context, :root_dir, :max_buffer_lines
84
84
  attr_accessor :init
85
85
 
86
- @instances = []
86
+ @instances = ObjectSpace::WeakMap.new
87
87
  @at_exit_installed = false
88
88
 
89
89
  def self.register_instance(mgr)
90
- @instances << mgr
90
+ @instances[mgr] = true
91
91
  return if @at_exit_installed
92
92
 
93
93
  @at_exit_installed = true
94
94
  at_exit do
95
95
  # Error-isolated sweep: one manager's kill_all raising must not
96
96
  # leave the remaining managers uncleaned at shutdown.
97
- @instances.each do |mgr|
97
+ @instances.each_key do |mgr|
98
98
  mgr.kill_all
99
99
  rescue StandardError => e
100
100
  Rubik::Log.warn(:runtime, "[TaskManager] at_exit kill_all failed: #{e.class}: #{e.message}")
@@ -4,6 +4,13 @@ module Rubik
4
4
  module Sandbox
5
5
  module Driver
6
6
  class Base
7
+ CONTAINER_HARDENING_FLAGS = [
8
+ "--read-only",
9
+ "--cap-drop", "ALL",
10
+ "--security-opt", "no-new-privileges",
11
+ "--tmpfs", "/tmp:rw,noexec,nosuid"
12
+ ].freeze
13
+
7
14
  attr_reader :options
8
15
 
9
16
  def initialize(options = {})
@@ -26,10 +26,7 @@ module Rubik
26
26
  docker_args = [
27
27
  "docker", "run", "--rm",
28
28
  "--name", container_name,
29
- "--read-only",
30
- "--cap-drop", "ALL",
31
- "--security-opt", "no-new-privileges",
32
- "--tmpfs", "/tmp:rw,noexec,nosuid",
29
+ *CONTAINER_HARDENING_FLAGS,
33
30
  "-w", "/workspace",
34
31
  "-v", "#{workspace}:/workspace:rw",
35
32
  "--memory", "#{memory_limit_mb}m",
@@ -21,6 +21,7 @@ module Rubik
21
21
 
22
22
  podman_args = [
23
23
  "podman", "run", "--rm",
24
+ *CONTAINER_HARDENING_FLAGS,
24
25
  "-w", "/workspace",
25
26
  "-v", "#{workspace}:/workspace:rw",
26
27
  "--memory", "#{memory_limit_mb}m",
@@ -143,7 +143,7 @@ module Rubik
143
143
  def verify_chdir_safety!(chdir)
144
144
  expanded = File.expand_path(chdir.to_s, @root_dir)
145
145
  safe = allowed_paths.any? do |allowed|
146
- Rubik::Platform.path_under?(expanded, allowed)
146
+ Rubik::Platform.resolved_path_under?(expanded, allowed)
147
147
  end
148
148
 
149
149
  unless safe
@@ -367,6 +367,8 @@ module Rubik
367
367
  return false if p =~ %r{\A[a-zA-Z]:(?![\\/])}
368
368
 
369
369
  return true if p =~ %r{\A/(?:\*|\.+)?/?\z}
370
+ # Root-anchored variable expansion (/$x, /$x/*, /${x}) can expand to / or /* when empty
371
+ return true if p =~ %r{\A/\$}
370
372
  return true if p =~ %r{\A[a-zA-Z]:[\\/](?:\*|\.+)?\z}i
371
373
  return true if HOME_TOKENS.include?(p) || p.start_with?("~/", "$HOME/", "${HOME}/")
372
374
 
@@ -272,7 +272,10 @@ module Rubik
272
272
  row = m[2].to_i
273
273
  return records.find { |r| r["type"] == type && r["row"] == row }
274
274
  end
275
- return records.find { |r| r["row"].to_s == selector } if selector.match?(/\A\d+\z/)
275
+ if selector.match?(/\A\d+\z/)
276
+ found = records.find { |r| r["row"].to_s == selector }
277
+ return found if found
278
+ end
276
279
  return records.find { |r| r["hash"].to_s.start_with?(selector.downcase) } if selector.match?(/\A[0-9a-f]{#{HASH_PREFIX_MIN},64}\z/i)
277
280
 
278
281
  # Son şans: alias — refs üzerinden tek sekme. Eski depolarda
@@ -13,6 +13,7 @@ module Rubik
13
13
  def initialize(coeffect_ctx: nil)
14
14
  @tools = {}
15
15
  @aliases = {}
16
+ @alias_owners = {}
16
17
  @tool_aliases = {}
17
18
  @origins = {}
18
19
  @coeffect_ctx = coeffect_ctx
@@ -24,32 +25,34 @@ module Rubik
24
25
  # while still allowing hot-updates of non-builtin tools.
25
26
  def register(tool_instance, aliases: [], origin: :builtin)
26
27
  @monitor.synchronize do
27
- @tools[tool_instance.name] = tool_instance
28
- @origins[tool_instance.name] = origin
28
+ name_str = tool_instance.name
29
+ clear_tool_aliases_unlocked(name_str)
30
+
31
+ @tools[name_str] = tool_instance
32
+ @origins[name_str] = origin
29
33
  all_aliases = (tool_instance.respond_to?(:aliases) ? Array(tool_instance.aliases) : []) + Array(aliases)
30
- @tool_aliases[tool_instance.name] ||= []
34
+ @tool_aliases[name_str] = []
31
35
  all_aliases.each do |al|
32
36
  clean_al = al.to_s.downcase
33
- @aliases[clean_al] = tool_instance.name
34
- @tool_aliases[tool_instance.name] << clean_al
37
+ owners = (@alias_owners[clean_al] ||= [])
38
+ owners.delete(name_str)
39
+ owners << name_str
40
+ @aliases[clean_al] = name_str
41
+ @tool_aliases[name_str] << clean_al unless @tool_aliases[name_str].include?(clean_al)
35
42
  end
36
43
  tool_instance
37
44
  end
38
45
  end
39
46
 
40
- def unregister(name)
47
+ def unregister(name, expected_instance = nil)
41
48
  @monitor.synchronize do
42
49
  canonical_name = @tools.key?(name.to_s) ? name.to_s : @aliases[name.to_s.downcase]
43
- removed_tool = @tools.delete(canonical_name) if canonical_name
44
- @origins.delete(canonical_name) if canonical_name
45
- if canonical_name && @tool_aliases[canonical_name]
46
- @tool_aliases.delete(canonical_name).each do |al|
47
- @aliases.delete(al) if @aliases[al] == canonical_name
48
- end
49
- else
50
- @aliases.delete_if { |_k, v| v == canonical_name || v == name.to_s }
51
- end
52
- @aliases.delete(name.to_s.downcase) if @aliases[name.to_s.downcase] == canonical_name
50
+ return nil unless canonical_name
51
+ return nil if expected_instance && !@tools[canonical_name].equal?(expected_instance)
52
+
53
+ removed_tool = @tools.delete(canonical_name)
54
+ @origins.delete(canonical_name)
55
+ clear_tool_aliases_unlocked(canonical_name)
53
56
  removed_tool
54
57
  end
55
58
  end
@@ -245,6 +248,23 @@ module Rubik
245
248
 
246
249
  @coeffect_ctx.satisfied?(deps)
247
250
  end
251
+
252
+ def clear_tool_aliases_unlocked(canonical_name)
253
+ old_aliases = @tool_aliases.delete(canonical_name) || []
254
+ old_aliases.each do |al|
255
+ owners = @alias_owners[al]
256
+ next unless owners
257
+
258
+ owners.delete(canonical_name)
259
+ if owners.empty?
260
+ @alias_owners.delete(al)
261
+ @aliases.delete(al)
262
+ else
263
+ @aliases[al] = owners.last
264
+ end
265
+ end
266
+ @aliases.delete_if { |_k, v| v == canonical_name }
267
+ end
248
268
  end
249
269
  end
250
270
  end
@@ -19,14 +19,16 @@ module Rubik
19
19
  module Capability
20
20
  FALSY_ENV_VALUES = ["0", "false", "no", "off"].freeze
21
21
 
22
+ OSC_ESCAPE_RE = /\e\][^\a\e]*(?:\a|\e\\|\z)/
23
+
22
24
  module_function
23
25
 
24
- # Strips ANSI SGR escape sequences from a string. Used on the recording
25
- # path (TeeIO -> StringIO) so session files and LLM context stay clean.
26
+ # Strips ANSI/CSI and OSC escape sequences from a string.
26
27
  def strip_ansi(str)
27
- return str unless str.is_a?(String) && str.include?("\e[")
28
+ return str unless str.is_a?(String) && str.include?("\e")
28
29
 
29
- Strings::ANSI.sanitize(str)
30
+ cleaned = str.gsub(OSC_ESCAPE_RE, "")
31
+ Strings::ANSI.sanitize(cleaned)
30
32
  end
31
33
 
32
34
  # True when ANSI color output is allowed for `io` under `config`.
@@ -79,6 +79,7 @@ module Rubik
79
79
  end
80
80
 
81
81
  def render_segment(segment)
82
+ segment = Rubik::UI::Capability.strip_ansi(segment)
82
83
  return segment unless @enabled
83
84
 
84
85
  line = segment.chomp
@@ -130,8 +130,10 @@ module Rubik
130
130
  def render_user_output(step_info)
131
131
  @spinner.stop
132
132
 
133
- header = @theme.paint("#{@theme.glyph(:branch)} #{step_info[:label]}", :dim)
134
- "#{header}\n#{step_info[:content]}\n"
133
+ label = Rubik::UI::Capability.strip_ansi(step_info[:label].to_s)
134
+ content = Rubik::UI::Capability.strip_ansi(step_info[:content].to_s)
135
+ header = @theme.paint("#{@theme.glyph(:branch)} #{label}", :dim)
136
+ "#{header}\n#{content}\n"
135
137
  end
136
138
 
137
139
  def render_tool_result(step_info)
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.11.0"
4
+ VERSION = "0.12.0"
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.11.0
4
+ version: 0.12.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Özgür Ulukır