rubik 0.12.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 (107) hide show
  1. checksums.yaml +4 -4
  2. data/ATTRIBUTION.md +1 -1
  3. data/CHANGELOG.md +71 -1
  4. data/bin/rubik +11 -1
  5. data/lib/rubik/ast/c_extractor.rb +1 -1
  6. data/lib/rubik/ast/graph.rb +38 -57
  7. data/lib/rubik/ast/graph_extensions.rb +57 -15
  8. data/lib/rubik/ast/ruby_extractor.rb +4 -0
  9. data/lib/rubik/ast/treesitter/c_walker.rb +11 -3
  10. data/lib/rubik/buffer/manager.rb +33 -11
  11. data/lib/rubik/buffer/snapshot.rb +23 -3
  12. data/lib/rubik/cli/connect.rb +49 -0
  13. data/lib/rubik/config/defaults.rb +4 -7
  14. data/lib/rubik/config/env_guard.rb +43 -0
  15. data/lib/rubik/config/schema.rb +8 -1
  16. data/lib/rubik/config/secret_policy.rb +6 -5
  17. data/lib/rubik/config.rb +1 -1
  18. data/lib/rubik/connect/http.rb +85 -0
  19. data/lib/rubik/connect/models_dev.rb +173 -0
  20. data/lib/rubik/connect/probes.rb +103 -0
  21. data/lib/rubik/connect/prompt_ui.rb +139 -0
  22. data/lib/rubik/connect/wizard.rb +540 -0
  23. data/lib/rubik/connect.rb +7 -0
  24. data/lib/rubik/context/repo_context_reader.rb +8 -4
  25. data/lib/rubik/llm/chunk_assembler.rb +12 -1
  26. data/lib/rubik/llm/formatter.rb +14 -0
  27. data/lib/rubik/llm/openai_compatible.rb +4 -1
  28. data/lib/rubik/llm/provider_key.rb +32 -0
  29. data/lib/rubik/llm/registry.rb +18 -2
  30. data/lib/rubik/llm/router.rb +19 -1
  31. data/lib/rubik/llm/session_header.rb +128 -0
  32. data/lib/rubik/llm/sse_parser.rb +57 -10
  33. data/lib/rubik/lsp/client.rb +11 -5
  34. data/lib/rubik/lsp/transport.rb +17 -7
  35. data/lib/rubik/mcp/transport/stdio.rb +42 -4
  36. data/lib/rubik/orchestrator/continuation_manager.rb +14 -5
  37. data/lib/rubik/orchestrator/goal_ledger/ledger.rb +18 -2
  38. data/lib/rubik/orchestrator/goal_ledger/observation_projection.rb +13 -4
  39. data/lib/rubik/orchestrator/goal_ledger/validator.rb +46 -7
  40. data/lib/rubik/orchestrator/goal_ledger/verifier.rb +8 -1
  41. data/lib/rubik/orchestrator/goal_session.rb +4 -4
  42. data/lib/rubik/orchestrator/loop.rb +8 -11
  43. data/lib/rubik/orchestrator/provider_resolver.rb +29 -6
  44. data/lib/rubik/orchestrator/step_executor.rb +17 -2
  45. data/lib/rubik/orchestrator/subagent/instance.rb +24 -1
  46. data/lib/rubik/orchestrator/subagent/notices.rb +1 -1
  47. data/lib/rubik/orchestrator/subagent/reaper.rb +21 -2
  48. data/lib/rubik/orchestrator/subagent/start_gate.rb +1 -1
  49. data/lib/rubik/orchestrator/subagent/step_runner.rb +7 -7
  50. data/lib/rubik/orchestrator/subagent/supervisor.rb +10 -3
  51. data/lib/rubik/orchestrator/turn_executor/user_channel.rb +27 -5
  52. data/lib/rubik/orchestrator/turn_executor.rb +24 -8
  53. data/lib/rubik/platform/filesystem.rb +52 -24
  54. data/lib/rubik/plugin/storage.rb +20 -0
  55. data/lib/rubik/prompt/context_builder.rb +2 -1
  56. data/lib/rubik/repair/loop.rb +22 -2
  57. data/lib/rubik/repl/commands/agent_context.rb +1 -1
  58. data/lib/rubik/repl/commands/agent_execution.rb +20 -15
  59. data/lib/rubik/repl/commands/buffer.rb +15 -0
  60. data/lib/rubik/repl/commands/connect.rb +51 -0
  61. data/lib/rubik/repl/commands/lsp.rb +1 -1
  62. data/lib/rubik/repl/commands/plugins.rb +31 -31
  63. data/lib/rubik/repl/commands/session.rb +5 -5
  64. data/lib/rubik/repl/commands/workspace.rb +4 -4
  65. data/lib/rubik/repl/commands.rb +2 -0
  66. data/lib/rubik/repl/input_execution.rb +30 -29
  67. data/lib/rubik/repl/input_loop.rb +10 -4
  68. data/lib/rubik/repl/lifecycle.rb +38 -0
  69. data/lib/rubik/repl/notice_router.rb +11 -5
  70. data/lib/rubik/repl/paste_support.rb +1 -1
  71. data/lib/rubik/repl/prompt_grace.rb +3 -3
  72. data/lib/rubik/repl/shell.rb +10 -2
  73. data/lib/rubik/repl/turn_recorder.rb +14 -3
  74. data/lib/rubik/runtime/context.rb +33 -27
  75. data/lib/rubik/runtime/manager.rb +23 -15
  76. data/lib/rubik/sandbox/driver/bubblewrap.rb +58 -8
  77. data/lib/rubik/sandbox/driver/process.rb +32 -1
  78. data/lib/rubik/sandbox/runner.rb +9 -1
  79. data/lib/rubik/security/classifier/classifier.rb +147 -13
  80. data/lib/rubik/security/classifier/commands/docker.yaml +1 -1
  81. data/lib/rubik/security/classifier/commands/git.yaml +27 -1
  82. data/lib/rubik/security/classifier/commands/sed.yaml +3 -3
  83. data/lib/rubik/security/classifier/database.rb +2 -2
  84. data/lib/rubik/security/command_gate.rb +8 -1
  85. data/lib/rubik/security/redactor.rb +62 -19
  86. data/lib/rubik/session/recorder.rb +13 -18
  87. data/lib/rubik/session/replayer.rb +29 -7
  88. data/lib/rubik/storage/store.rb +19 -5
  89. data/lib/rubik/tools/builtins/exec.rb +1 -1
  90. data/lib/rubik/tools/builtins/files.rb +8 -12
  91. data/lib/rubik/tools/builtins/grep.rb +3 -2
  92. data/lib/rubik/tools/builtins/lsp.rb +31 -7
  93. data/lib/rubik/tools/builtins/show_file.rb +1 -1
  94. data/lib/rubik/tools/builtins/synthesis.rb +4 -4
  95. data/lib/rubik/tools/result_normalizer.rb +1 -1
  96. data/lib/rubik/ui/banner.rb +3 -3
  97. data/lib/rubik/ui/dialog.rb +10 -7
  98. data/lib/rubik/ui/diff_viewer.rb +4 -4
  99. data/lib/rubik/ui/frame.rb +13 -3
  100. data/lib/rubik/ui/markdown_stream.rb +8 -2
  101. data/lib/rubik/ui/panel.rb +11 -11
  102. data/lib/rubik/ui/renderer.rb +6 -6
  103. data/lib/rubik/ui/spinner.rb +1 -1
  104. data/lib/rubik/ui/statusline.rb +3 -3
  105. data/lib/rubik/ui/theme.rb +1 -1
  106. data/lib/rubik/version.rb +1 -1
  107. metadata +12 -1
@@ -20,8 +20,27 @@ module Rubik
20
20
  # kalır ve validate içinde implicit self ile erişilir.
21
21
  extend DeepOps
22
22
 
23
+ # Σ belgesi cap'lidir (üstteki sözleşme): alan uzunlukları ve patch
24
+ # boyutu zaten sınırlıydı; koleksiyon başına öğe sayısı da sınırlanır.
25
+ # Yoksa pinli tek Σ satırı (refresh_in_history!) her adımda sınırsız
26
+ # büyür ve hiçbir compaction tier'ı onu küçültemez. SSOT burasıdır —
27
+ # Ledger.load da aynı tavanı okur.
28
+ MAX_ITEMS_PER_COLLECTION = 200
29
+
23
30
  module_function
24
31
 
32
+ # Σ gövde şekli kapısı (Ledger.load): koleksiyonlar dizi, madde
33
+ # listeleri Hash, skalar liste String olmalı; tavan SSOT burada.
34
+ def sigma_doc_well_formed?(doc, schema:)
35
+ return false unless doc.is_a?(Hash) && doc["rev"].is_a?(Integer) && doc["objective"]
36
+
37
+ schema.sections.all? do |name, spec|
38
+ coll = doc[name]
39
+ coll.is_a?(Array) && coll.size <= MAX_ITEMS_PER_COLLECTION &&
40
+ coll.all?(spec.item ? Hash : String)
41
+ end
42
+ end
43
+
25
44
  # patch_or_text: String (önce parse edilir) | GoalLedger::Patch
26
45
  # -> [:ok, new_doc, new_rev] | [:rejected, [reason, ...]]
27
46
  # Model girdisinde ASLA raise etmez (her başarısızlık veridir);
@@ -139,7 +158,7 @@ module Rubik
139
158
  return [err] if err
140
159
 
141
160
  coll << op[:value]
142
- return []
161
+ return collection_cap_rejection(op, name, coll)
143
162
  end
144
163
 
145
164
  idx = index_token(idx_tok, name, coll, op, insertable: op[:op] == :add)
@@ -148,14 +167,17 @@ module Rubik
148
167
  err = op[:op] == :remove ? nil : check_value(spec, op[:value], name, op)
149
168
  return [err] if err
150
169
 
151
- if op[:op] == :add
170
+ case op[:op]
171
+ when :add
152
172
  coll.insert(idx, op[:value])
153
- elsif op[:op] == :replace
173
+ collection_cap_rejection(op, name, coll)
174
+ when :replace
154
175
  coll[idx] = op[:value]
176
+ []
155
177
  else
156
178
  coll.delete_at(idx)
179
+ []
157
180
  end
158
- []
159
181
  end
160
182
 
161
183
  # ---- item listesi (tasks/findings/...) ----
@@ -179,7 +201,7 @@ module Rubik
179
201
  return errs unless errs.empty?
180
202
 
181
203
  coll << op[:value]
182
- return dup_id_rejections(coll, spec, name, op)
204
+ return dup_id_rejections(coll, spec, name, op) + collection_cap_rejection(op, name, coll)
183
205
  end
184
206
 
185
207
  idx = index_token(idx_tok, name, coll, op, insertable: op[:op] == :add)
@@ -193,8 +215,13 @@ module Rubik
193
215
  errs = validate_item_object(spec, op[:value], name, op)
194
216
  return errs unless errs.empty?
195
217
 
196
- op[:op] == :add ? coll.insert(idx, op[:value]) : coll[idx] = op[:value]
197
- dup_id_rejections(coll, spec, name, op)
218
+ if op[:op] == :add
219
+ coll.insert(idx, op[:value])
220
+ dup_id_rejections(coll, spec, name, op) + collection_cap_rejection(op, name, coll)
221
+ else
222
+ coll[idx] = op[:value]
223
+ dup_id_rejections(coll, spec, name, op)
224
+ end
198
225
  end
199
226
 
200
227
  def field_op(op, name, spec, coll, idx_tok)
@@ -327,6 +354,18 @@ module Rubik
327
354
  "use a numeric index for replace/remove")
328
355
  end
329
356
 
357
+ # Koleksiyon başına öğe tavanı: yalnız BÜYÜTEN op'lar reddedilir;
358
+ # replace/remove her zaman geçer (mevcut fazla öğeler temizlenebilir).
359
+ # Working copy zaten mutasyona uğramış olsa da ret tüm patch'i çöpe
360
+ # atar — current_doc dokunulmaz (atomiklik korunur).
361
+ def collection_cap_rejection(op, name, coll)
362
+ return [] if coll.size <= MAX_ITEMS_PER_COLLECTION
363
+
364
+ [rejection(:schema, op[:index], op[:path],
365
+ "#{name} is at its cap of #{MAX_ITEMS_PER_COLLECTION} items",
366
+ "remove an existing #{name} item before adding another")]
367
+ end
368
+
330
369
  def dup_id_rejections(coll, spec, name, op)
331
370
  return [] unless spec.id_field
332
371
 
@@ -93,9 +93,16 @@ module Rubik
93
93
  # Kesilmiş okumada needle yokluğu KANITLANAMAZ → unknown (tri-state
94
94
  # dürüstlüğünün kalbi); tam okumada yokluk gerçek yokluktur → failed.
95
95
  def needle_read(spec, expanded)
96
- size = File.size(expanded)
96
+ # Missing path is a proven false (same contract as file_exists) — never
97
+ # let Errno::ENOENT fall through to the generic :unknown rescue.
98
+ return [:failed, "file_contains #{spec[:path]}: missing"] unless File.exist?(expanded)
97
99
  return [:failed, "file_contains #{spec[:path]}: path is a directory"] if File.directory?(expanded)
100
+ # A FIFO/socket/device reports File.size == 0 and File.open would block
101
+ # forever waiting for a writer (the verify path is model-authored).
102
+ # Reject non-regular files up front so they report :unknown, never hang.
103
+ return [:unknown, "file_contains #{spec[:path]}: not a regular file"] unless File.file?(expanded)
98
104
 
105
+ size = File.size(expanded)
99
106
  body = File.open(expanded, "rb") { |f| f.read(VerifySpec::READ_CAP_BYTES) }.to_s
100
107
  body = Rubik::Platform.safe_utf8(body)
101
108
  return [:ok, "file_contains"] if body.include?(spec[:needle])
@@ -203,8 +203,8 @@ module Rubik
203
203
  while !res[:ok] && res[:reason] == :budget_exhausted
204
204
  if auto_extensions < max_auto
205
205
  auto_extensions += 1
206
- ctx.out.puts "\n🤖 [Rubik::Goal] Adım bütçesi doldu (#{res[:error]}). " \
207
- "Otonom devam hakkı (#{auto_extensions}/#{max_auto}) kullanılarak +20 adım ekleniyor..."
206
+ ctx.out.puts "\n🤖 [Rubik::Goal] Step budget exhausted (#{res[:error]}). " \
207
+ "Using autonomous continue allowance (#{auto_extensions}/#{max_auto}), +20 steps are being added..."
208
208
  goal_state.extend!(goal_state.max_steps + 20)
209
209
  res = orchestrator.continue_loop(20, auto: true)
210
210
  next
@@ -213,10 +213,10 @@ module Rubik
213
213
  break unless Rubik::Storage::Layout.config_get(ctx.config, "agent.ask_continue_on_limit", true)
214
214
 
215
215
  ctx.out.puts "\n⚠️ [Rubik::Goal] #{res[:error]}"
216
- ans = ctx.ask_yes_no(" [Rubik::Goal] +20 adım ile devam edilsin mi?", default: "n")
216
+ ans = ctx.ask_yes_no(" [Rubik::Goal] Continue with +20 steps?", default: "n")
217
217
  break unless ["y", "yes", "evet"].include?(ans)
218
218
 
219
- ctx.out.puts " [Rubik::Goal] Adım bütçesi +20 artırılıyor ve hedef sürdürülüyor..."
219
+ ctx.out.puts " [Rubik::Goal] Increasing step budget by +20 and resuming the goal..."
220
220
  goal_state.extend!(goal_state.max_steps + 20)
221
221
  res = orchestrator.continue_loop(20)
222
222
  end
@@ -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"],