rubik 0.10.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 (83) hide show
  1. checksums.yaml +4 -4
  2. data/ATTRIBUTION.md +1 -1
  3. data/CHANGELOG.md +117 -1
  4. data/lib/rubik/ast/extractor.rb +2 -1
  5. data/lib/rubik/ast/treesitter_extractor.rb +2 -1
  6. data/lib/rubik/benchmark/vakanuvis_adoption.rb +2 -1
  7. data/lib/rubik/buffer/manager.rb +3 -3
  8. data/lib/rubik/config/deep_ops.rb +3 -1
  9. data/lib/rubik/config/defaults.rb +8 -8
  10. data/lib/rubik/config/schema.rb +7 -0
  11. data/lib/rubik/config/secret_policy.rb +20 -10
  12. data/lib/rubik/config/store.rb +2 -1
  13. data/lib/rubik/config.rb +3 -3
  14. data/lib/rubik/context/ignore_rules.rb +193 -0
  15. data/lib/rubik/context/scanner.rb +46 -161
  16. data/lib/rubik/llm/anthropic.rb +2 -1
  17. data/lib/rubik/llm/client.rb +28 -206
  18. data/lib/rubik/llm/connection_pool.rb +104 -0
  19. data/lib/rubik/llm/formatter.rb +4 -1
  20. data/lib/rubik/llm/ollama.rb +2 -1
  21. data/lib/rubik/llm/openai_compatible.rb +2 -1
  22. data/lib/rubik/llm/registry.rb +3 -2
  23. data/lib/rubik/llm/router.rb +6 -1
  24. data/lib/rubik/llm/sse_parser.rb +113 -0
  25. data/lib/rubik/lsp/circuit_breaker.rb +98 -0
  26. data/lib/rubik/lsp/client_provisioner.rb +49 -0
  27. data/lib/rubik/lsp/manager.rb +55 -88
  28. data/lib/rubik/mcp/manager.rb +39 -14
  29. data/lib/rubik/mcp/proxy_tool.rb +2 -2
  30. data/lib/rubik/mcp/transport/stdio.rb +3 -2
  31. data/lib/rubik/orchestrator/auto_apply.rb +4 -3
  32. data/lib/rubik/orchestrator/goal_ledger/ledger.rb +12 -1
  33. data/lib/rubik/orchestrator/goal_ledger/schema_vocabulary.rb +38 -0
  34. data/lib/rubik/orchestrator/goal_ledger/xml_render.rb +6 -1
  35. data/lib/rubik/orchestrator/goal_ledger.rb +1 -0
  36. data/lib/rubik/orchestrator/goal_state.rb +6 -2
  37. data/lib/rubik/orchestrator/loop.rb +30 -6
  38. data/lib/rubik/orchestrator/lsp_feedback.rb +1 -1
  39. data/lib/rubik/orchestrator/provider_resolver.rb +12 -0
  40. data/lib/rubik/orchestrator/step_executor.rb +2 -1
  41. data/lib/rubik/orchestrator/subagent/notices.rb +2 -2
  42. data/lib/rubik/orchestrator/subagent/step_runner.rb +7 -0
  43. data/lib/rubik/orchestrator/subagent/transcript_formatter.rb +2 -1
  44. data/lib/rubik/platform/filesystem.rb +2 -2
  45. data/lib/rubik/platform/io_drain.rb +3 -1
  46. data/lib/rubik/plugin/storage.rb +8 -8
  47. data/lib/rubik/repair/loop.rb +1 -1
  48. data/lib/rubik/repl/config_wiring.rb +5 -3
  49. data/lib/rubik/repl/input_execution.rb +147 -7
  50. data/lib/rubik/repl/lifecycle.rb +1 -1
  51. data/lib/rubik/repl/shell.rb +9 -1
  52. data/lib/rubik/repl/tee_io.rb +2 -1
  53. data/lib/rubik/runtime/ast_service.rb +2 -1
  54. data/lib/rubik/runtime/fiber.rb +1 -0
  55. data/lib/rubik/runtime/manager.rb +4 -1
  56. data/lib/rubik/runtime/overlay_storage.rb +17 -17
  57. data/lib/rubik/runtime/task_manager.rb +4 -4
  58. data/lib/rubik/sandbox/driver/base.rb +7 -0
  59. data/lib/rubik/sandbox/driver/docker.rb +1 -4
  60. data/lib/rubik/sandbox/driver/podman.rb +1 -0
  61. data/lib/rubik/sandbox/runner.rb +6 -5
  62. data/lib/rubik/security/audit_log.rb +2 -1
  63. data/lib/rubik/security/classifier/classifier.rb +2 -0
  64. data/lib/rubik/security/command_gate.rb +11 -152
  65. data/lib/rubik/security/guard.rb +1 -1
  66. data/lib/rubik/security/secret_store.rb +32 -3
  67. data/lib/rubik/security/segment_report.rb +161 -0
  68. data/lib/rubik/session/recorder.rb +2 -1
  69. data/lib/rubik/skills/manager.rb +2 -1
  70. data/lib/rubik/storage/store.rb +4 -1
  71. data/lib/rubik/storage/transcript_indexer.rb +3 -2
  72. data/lib/rubik/storage/vakanuvis.rb +2 -1
  73. data/lib/rubik/tools/builtins/goal_ledger.rb +12 -1
  74. data/lib/rubik/tools/builtins/synthesis.rb +3 -3
  75. data/lib/rubik/tools/preflight_runner.rb +2 -1
  76. data/lib/rubik/tools/registry.rb +36 -16
  77. data/lib/rubik/tools/uri_resolver.rb +3 -2
  78. data/lib/rubik/ui/capability.rb +7 -4
  79. data/lib/rubik/ui/markdown_stream.rb +1 -0
  80. data/lib/rubik/ui/renderer.rb +4 -2
  81. data/lib/rubik/version.rb +1 -1
  82. data/lib/rubik.rb +3 -3
  83. metadata +8 -1
@@ -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
 
@@ -136,7 +139,7 @@ module Rubik
136
139
  client =
137
140
  if @client_factory
138
141
  @client_factory.call(cmd, args: args, env: env, **inherit_env_kwarg, name: name_str, root_dir: @root_dir,
139
- guard: @guard || (base_ctx ? Rubik::Coeffects.get(base_ctx, Rubik::Coeffects::GUARD) : nil))
142
+ guard: resolve_guard(base_ctx))
140
143
  else
141
144
  Rubik::MCP::Client.new(
142
145
  cmd,
@@ -148,7 +151,7 @@ module Rubik
148
151
  # Manager built before wire_runtime_context still picks up the
149
152
  # session guard once the context provides it (construction-time
150
153
  # snapshots of coeffects go stale — this matches base_ctx above).
151
- guard: @guard || (base_ctx ? Rubik::Coeffects.get(base_ctx, Rubik::Coeffects::GUARD) : nil),
154
+ guard: resolve_guard(base_ctx),
152
155
  call_timeout: call_timeout
153
156
  )
154
157
  end
@@ -169,6 +172,24 @@ module Rubik
169
172
  end
170
173
  end
171
174
 
175
+ # The single boot race gate (D5), checked at apply time under the
176
+ # monitor: a disable/remove/enable during boot wins over the boot's
177
+ # own apply, and a stop_all skips it entirely. Epoch-complete: this
178
+ # boot may only apply into the slot its own phase-0 claim marked,
179
+ # so a user decision that moved the slot or a newer boot's fresh
180
+ # mark wins. Callers hold @monitor.
181
+ def boot_gate_open?(name_str, epoch)
182
+ !@stopped && @statuses[name_str] == :connecting && @boot_marks[name_str].equal?(epoch)
183
+ end
184
+
185
+ # Resolved live at connect time: the composed kwarg wins, but a
186
+ # Manager built before wire_runtime_context still picks up the
187
+ # session guard once the context provides it (construction-time
188
+ # snapshots of coeffects go stale — matches base_ctx).
189
+ def resolve_guard(base_ctx)
190
+ @guard || (base_ctx ? Rubik::Coeffects.get(base_ctx, Rubik::Coeffects::GUARD) : nil)
191
+ end
192
+
172
193
  # Apply phase of enable_server: the post-connect half, extracted
173
194
  # verbatim — context wiring FIRST (so any later failure cleans up via
174
195
  # the child drain), proxy registration, registry flips, and the
@@ -197,9 +218,19 @@ module Rubik
197
218
  if @tools_registry
198
219
  tools.each do |tdef|
199
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
200
231
  @tools_registry.register(proxy, origin: :mcp)
201
232
  server_tools << proxy
202
- server_ctx.on_dispose { @tools_registry.unregister(proxy.name) }
233
+ server_ctx.on_dispose { @tools_registry.unregister(proxy.name, proxy) }
203
234
  end
204
235
  end
205
236
 
@@ -247,7 +278,7 @@ module Rubik
247
278
  end
248
279
 
249
280
  @monitor.synchronize do
250
- if @stopped || @statuses[name_str] != :connecting || !@boot_marks[name_str].equal?(epoch)
281
+ unless boot_gate_open?(name_str, epoch)
251
282
  safely_stop_rolled_back_client(connected[:client], name_str)
252
283
  return @clients[name_str]
253
284
  end
@@ -365,22 +396,16 @@ module Rubik
365
396
  # only receives the decision.
366
397
  def boot_apply_gate(name_str, parsed_defn, boot_epoch, client:, tools:)
367
398
  @monitor.synchronize do
368
- # Single race gate (D5), checked at apply time under the
369
- # monitor: a disable/remove/enable during boot wins over
370
- # the boot's own apply, and a stop_all skips it entirely.
371
- # Epoch-complete gate: this boot may only apply into the
372
- # slot its own phase-0 claim marked, so a user decision
373
- # that moved the slot or a newer boot's fresh mark wins.
374
399
  # In the synchronous path nothing can interleave, so the
375
- # guard is provably inert there.
376
- if @stopped || @statuses[name_str] != :connecting || !@boot_marks[name_str].equal?(boot_epoch)
377
- :skipped
378
- else
400
+ # gate is provably inert there.
401
+ if boot_gate_open?(name_str, boot_epoch)
379
402
  apply_connected_server(name_str, parsed_defn, client: client, tools: tools)
380
403
  # Post-apply revalidation under the boot actor: a no-op
381
404
  # when apply already landed :active.
382
405
  transition_server!(name_str, :active, epoch: boot_epoch)
383
406
  :applied
407
+ else
408
+ :skipped
384
409
  end
385
410
  end
386
411
  end
@@ -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
 
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "../log"
3
4
  require_relative "subagent/notices"
4
5
  require_relative "../storage/layout"
5
6
 
@@ -109,11 +110,11 @@ module Rubik
109
110
  Subagent::Notices.emit(event_bus, Subagent::Notices::AUTO_APPLY_FAILED_EVENT,
110
111
  { id: id, role: role, state: state.to_s, reason: reason })
111
112
  else
112
- warn("[AutoApply] subagent '#{id}' auto-apply (#{trigger}) failed: #{reason}")
113
+ Rubik::Log.warn(:orchestrator, "[AutoApply] subagent '#{id}' auto-apply (#{trigger}) failed: #{reason}")
113
114
  end
114
115
  rescue StandardError => e
115
- warn("[AutoApply] subagent '#{id}' auto-apply (#{trigger}) failed: #{reason} " \
116
- "(notice emit also failed: #{e.class}: #{e.message})")
116
+ Rubik::Log.warn(:orchestrator, "[AutoApply] subagent '#{id}' auto-apply (#{trigger}) failed: #{reason} " \
117
+ "(notice emit also failed: #{e.class}: #{e.message})")
117
118
  end
118
119
  end
119
120
 
@@ -87,6 +87,13 @@ module Rubik
87
87
  config_get(config, "goal.ledger.max_patch_retries", DEFAULT_MAX_RETRIES).to_i
88
88
  end
89
89
 
90
+ # Model-yüzü sözlük: SchemaVocabulary'ün PRODUCTION_SCHEMA'dan
91
+ # türettiği tek satır (frozen şema → memoize güvenli). Tool
92
+ # description'ı ile tükenme feedback'i bu tek türevi paylaşır.
93
+ def schema_vocabulary
94
+ @schema_vocabulary ||= SchemaVocabulary.render(PRODUCTION_SCHEMA)
95
+ end
96
+
90
97
  def create!(goal_text:, config: nil, store: nil, dmesg: nil, event_bus: nil)
91
98
  ledger = new(goal_text: goal_text.to_s, max_retries: max_patch_retries(config),
92
99
  store: store, dmesg: dmesg, event_bus: event_bus)
@@ -142,8 +149,12 @@ module Rubik
142
149
  # Ret sayacı ardışıktır; başarı sıfırlar; bütçe aşımında :exhausted
143
150
  # döner ve ESKİ Σ korunur (goal loop asla brick olmaz).
144
151
  def update(patch_or_text)
145
- verdict = Validator.validate(patch_or_text, schema: PRODUCTION_SCHEMA, current_doc: @doc)
146
152
  @monitor.synchronize do
153
+ # Validation reads @doc; keep it inside the monitor so a
154
+ # concurrent reader/writer cannot slip between validate and
155
+ # apply! (validation is pure — no IO — so holding the lock is
156
+ # free of deadlock risk).
157
+ verdict = Validator.validate(patch_or_text, schema: PRODUCTION_SCHEMA, current_doc: @doc)
147
158
  if verdict[0] == :ok
148
159
  apply!(verdict[1])
149
160
  elsif @rejections >= @max_retries
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rubik
4
+ module Orchestrator
5
+ module GoalLedger
6
+ # Model-yüzü sözlük türetme yüzeyi. SSOT disiplini: Σ şemasının tek
7
+ # gerçek kaynağı Ledger::PRODUCTION_SCHEMA'dır; enum/required/optional
8
+ # bilgisi buradan TEK noktadan türetilir ve üç statik teaching yüzeyine
9
+ # dağıtılır (tool description — yüklenme anı, Σ XML sayfası — her adım
10
+ # başı reinject, tükenme feedback'i). Elle yazılan enum/alan kopyası
11
+ # YOKTUR: şema değişirse sözlük değişir. Durum-bağımsızdır — rev/drift
12
+ # ile hiçbir ilişkisi olmadığı için bayatlayamaz (drift felsefesi:
13
+ # bayat teşhis bilgi zehridir; sözlük teşhis değil, gramerdir) ve tek
14
+ # sabit satır olduğu için pinli Σ satırını şişirmez.
15
+ module SchemaVocabulary
16
+ module_function
17
+
18
+ # Tek satırlık, deterministik sözlük: item-section'lar için alan
19
+ # mühürleri (* required, ? optional) ve enum dağarcığı, skalar
20
+ # listeler için tip. Hash ekleme sırası korunur → deterministik.
21
+ def render(schema)
22
+ sections = schema.sections.map do |name, section|
23
+ if section.scalar
24
+ "#{name}:string-list"
25
+ else
26
+ fields = section.item.fields.map do |fname, spec|
27
+ "#{fname}#{spec.optional ? '?' : '*'}#{":#{spec.enum.join('|')}" if spec.enum}"
28
+ end
29
+ "#{name}(#{fields.join(',')})"
30
+ end
31
+ end
32
+ "#{sections.join(' ')} — * required, ? optional; append items via /<section>/-, " \
33
+ "one op per item; wholesale section writes are rejected"
34
+ end
35
+ end
36
+ end
37
+ end
38
+ end
@@ -28,6 +28,11 @@ module Rubik
28
28
  attrs += %( updated_at="#{@updated_at.utc.iso8601}") if @updated_at
29
29
  body = []
30
30
  body << %( <objective>#{esc.call(@doc['objective'].to_s)}</objective>)
31
+ # Statik gramer sözlüğü (Ledger.schema_vocabulary — SSOT türetme):
32
+ # durum-bağımsız tek satır; pinli Σ satırına sabit maliyet, modele
33
+ # kullanım anının dibinde kalıcı öğretim ("yokluk, boşluk değil"
34
+ # kuralı koleksiyonlar içindir — sözlük koleksiyon değildir).
35
+ body << %( <vocabulary>#{esc.call(Ledger.schema_vocabulary)}</vocabulary>)
31
36
  tasks = @doc["tasks"].each_with_index.map do |task, idx|
32
37
  text = task["title"].to_s
33
38
  text += " — notes: #{task['notes']}" if task["notes"]
@@ -38,7 +43,7 @@ module Rubik
38
43
  end
39
44
  body << "<tasks>\n#{tasks.join("\n")}\n </tasks>" unless tasks.empty?
40
45
  findings = @doc["findings"].each_with_index.map do |f, idx|
41
- %( <finding id="#{esc.call(f['id'].to_s)}" source_step="#{f['source_step']}" index="#{idx}">#{esc.call(f['text'].to_s)}</finding>)
46
+ %( <finding id="#{esc.call(f['id'].to_s)}" source_step="#{esc.call(f['source_step'].to_s)}" index="#{idx}">#{esc.call(f['text'].to_s)}</finding>)
42
47
  end
43
48
  body << "<findings>\n#{findings.join("\n")}\n </findings>" unless findings.empty?
44
49
  decisions = @doc["decisions"].each_with_index.map do |dec, idx|
@@ -57,6 +57,7 @@ end
57
57
 
58
58
  require_relative "goal_ledger/patch"
59
59
  require_relative "goal_ledger/schema"
60
+ require_relative "goal_ledger/schema_vocabulary"
60
61
  require_relative "goal_ledger/validator"
61
62
  require_relative "goal_ledger/ledger"
62
63
  require_relative "goal_ledger/verify_spec"
@@ -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
@@ -37,7 +37,7 @@ module Rubik
37
37
  # review, Plan 87). warn keeps the failure visible on stderr;
38
38
  # ANSI stripping keeps LSP-server-controlled messages from
39
39
  # injecting terminal escape sequences (red-team E1).
40
- warn("LSP sync skipped: #{e.message.gsub(/\e\[[0-9;]*[A-Za-z]/, '')}")
40
+ Rubik::Log.warn(:lsp, "LSP sync skipped: #{e.message.gsub(/\e\[[0-9;]*[A-Za-z]/, '')}")
41
41
  tool_result
42
42
  end
43
43
 
@@ -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,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "../log"
3
4
  require_relative "finish_message_selector"
4
5
  require_relative "auto_apply"
5
6
  require_relative "tool_call_id"
@@ -217,7 +218,7 @@ module Rubik
217
218
  sink.call(type: :user_output, content: raw_output.to_s, label: raw_output.display_stub,
218
219
  step: @deps.step_count, max_steps: @deps.max_steps)
219
220
  else
220
- warn("[show_file] no :user_output sink wired — display content dropped: #{raw_output.display_stub}")
221
+ Rubik::Log.warn(:orchestrator, "[show_file] no :user_output sink wired — display content dropped: #{raw_output.display_stub}")
221
222
  end
222
223
 
223
224
  Rubik::Tools::Result.new(
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "../../log"
3
4
  require_relative "../../events"
4
5
  require_relative "../../platform"
5
6
  require_relative "budget"
@@ -69,7 +70,7 @@ module Rubik
69
70
  rescue StandardError => e
70
71
  raise if fallback.nil?
71
72
 
72
- warn("#{fallback} (#{e.class}: #{e.message})")
73
+ Rubik::Log.warn(:orchestrator, "#{fallback} (#{e.class}: #{e.message})")
73
74
  end
74
75
 
75
76
  def normalize(event_name, payload)
@@ -191,7 +192,6 @@ module Rubik
191
192
  end
192
193
 
193
194
  DEFAULT_WAIT_TIMEOUT = 30
194
-
195
195
  def render_ids(ids) = "[#{Array(ids).map { |id| "'#{id}'" }.join(', ')}]"
196
196
 
197
197
  def wait_hint(ids, timeout: DEFAULT_WAIT_TIMEOUT) = "manage_subagents(action: 'wait', conversation_ids: #{render_ids(ids)}, timeout: #{timeout})"
@@ -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
@@ -3,6 +3,7 @@
3
3
  require "fileutils"
4
4
  require "json"
5
5
  require "digest"
6
+ require_relative "../../log"
6
7
  require_relative "../../security/redactor"
7
8
  require_relative "../../storage/layout"
8
9
  require_relative "../../tools/truncator"
@@ -56,7 +57,7 @@ module Rubik
56
57
  File.write(file_path, text)
57
58
  file_path
58
59
  rescue StandardError => e
59
- warn("[Subagent transcript] Failed to save #{file_path}: #{e.class}: #{e.message}")
60
+ Rubik::Log.warn(:orchestrator, "[Subagent transcript] Failed to save #{file_path}: #{e.class}: #{e.message}")
60
61
  nil
61
62
  end
62
63
 
@@ -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)
@@ -1,5 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "../log"
4
+
3
5
  module Rubik
4
6
  module Platform
5
7
  # Continuously drains a child-process IO (stderr) so a chatty child
@@ -34,7 +36,7 @@ module Rubik
34
36
  # time it is the watchdog dying while the child may still flood
35
37
  # the pipe — the exact deadlock this class exists to prevent —
36
38
  # so it must leave a trace.
37
- warn "[rubik] stderr drain died unexpectedly (#{e.class}: #{e.message})" unless @stopped
39
+ Rubik::Log.warn(:platform, "[rubik] stderr drain died unexpectedly (#{e.class}: #{e.message})") unless @stopped
38
40
  end
39
41
  self
40
42
  end
@@ -79,10 +79,10 @@ module Rubik
79
79
  when :verified
80
80
  :verified
81
81
  when :drift
82
- warn "[SECURITY] Integrity check failed for plugin '#{basename}': file modified since adding."
82
+ Rubik::Log.warn(:plugin, "[SECURITY] Integrity check failed for plugin '#{basename}': file modified since adding.")
83
83
  :rejected
84
84
  when :unknown
85
- warn "[SECURITY] Unknown plugin file '#{basename}' not in manifest. Skipping."
85
+ Rubik::Log.warn(:plugin, "[SECURITY] Unknown plugin file '#{basename}' not in manifest. Skipping.")
86
86
  :rejected
87
87
  end
88
88
  end
@@ -247,8 +247,8 @@ module Rubik
247
247
  entry = load_manifest(dir)[name]
248
248
 
249
249
  unless entry.is_a?(Hash) && entry["type"] == "directory" && entry["files"].is_a?(Hash)
250
- warn "[SECURITY] Directory plugin '#{name}' has no package inventory in the manifest " \
251
- "(legacy manifest). Skipping; re-add it with '!plugin add' or set RUBIK_TRUST_OVERLAYS=1 to trust it."
250
+ Rubik::Log.warn(:plugin, "[SECURITY] Directory plugin '#{name}' has no package inventory in the manifest " \
251
+ "(legacy manifest). Skipping; re-add it with '!plugin add' or set RUBIK_TRUST_OVERLAYS=1 to trust it.")
252
252
  return :rejected
253
253
  end
254
254
 
@@ -256,16 +256,16 @@ module Rubik
256
256
  begin
257
257
  current = PackageInventory.inventory(package_dir)
258
258
  rescue PackageInventory::Violation => e
259
- warn "[SECURITY] Integrity check failed for plugin package '#{name}': #{e.message}. " \
260
- "Re-add it with '!plugin add' or set RUBIK_TRUST_OVERLAYS=1 to trust it."
259
+ Rubik::Log.warn(:plugin, "[SECURITY] Integrity check failed for plugin package '#{name}': #{e.message}. " \
260
+ "Re-add it with '!plugin add' or set RUBIK_TRUST_OVERLAYS=1 to trust it.")
261
261
  return :rejected
262
262
  end
263
263
 
264
264
  drift = PackageInventory.drift(entry["files"], current)
265
265
  return :verified if drift.empty?
266
266
 
267
- warn "[SECURITY] Integrity check failed for plugin package '#{name}': #{drift}. " \
268
- "Re-add it with '!plugin add' or set RUBIK_TRUST_OVERLAYS=1 to trust it."
267
+ Rubik::Log.warn(:plugin, "[SECURITY] Integrity check failed for plugin package '#{name}': #{drift}. " \
268
+ "Re-add it with '!plugin add' or set RUBIK_TRUST_OVERLAYS=1 to trust it.")
269
269
  :rejected
270
270
  end
271
271
  end
@@ -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
@@ -1,5 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "../log"
4
+
3
5
  module Rubik
4
6
  module REPL
5
7
  # Wires reactive configuration observers to Shell subsystems.
@@ -60,7 +62,7 @@ module Rubik
60
62
  # only, so the mirror pushed writes into a key nothing reads back.
61
63
  # The incantation stays accepted; it warns instead of mirroring.
62
64
  cleanups << config.on_change("network.allow") do |_key, _val, _old|
63
- warn "[ConfigWiring] [DEPRECATION] Config key 'network.allow' is deprecated and has no effect. Use 'sandbox.allow_network' instead."
65
+ Rubik::Log.warn(:config, "[ConfigWiring] [DEPRECATION] Config key 'network.allow' is deprecated and has no effect. Use 'sandbox.allow_network' instead.")
64
66
  end
65
67
 
66
68
  cleanups
@@ -83,7 +85,7 @@ module Rubik
83
85
  begin
84
86
  shell.guard.verify_root_safety!(r)
85
87
  rescue Rubik::Security::BlockedWriteError => e
86
- warn "[ConfigWiring] #{e.message}. Skipping additional root #{r}."
88
+ Rubik::Log.warn(:config, "[ConfigWiring] #{e.message}. Skipping additional root #{r}.")
87
89
  next
88
90
  end
89
91
  end
@@ -110,7 +112,7 @@ module Rubik
110
112
  begin
111
113
  shell.guard.verify_root_safety!(d)
112
114
  rescue Rubik::Security::BlockedWriteError => e
113
- warn "[ConfigWiring] #{e.message}. Skipping allowed directory #{d}."
115
+ Rubik::Log.warn(:config, "[ConfigWiring] #{e.message}. Skipping allowed directory #{d}.")
114
116
  next
115
117
  end
116
118
  end