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
@@ -7,6 +7,7 @@ require_relative "commands/session"
7
7
  require_relative "commands/workspace"
8
8
  require_relative "commands/lsp"
9
9
  require_relative "commands/agent"
10
+ require_relative "commands/connect"
10
11
  require_relative "commands/plugins"
11
12
  require_relative "commands/mcp"
12
13
  require_relative "commands/skills"
@@ -26,6 +27,7 @@ module Rubik
26
27
  Workspace,
27
28
  Lsp,
28
29
  Agent,
30
+ Connect,
29
31
  Plugins,
30
32
  Mcp,
31
33
  Skills,
@@ -57,7 +57,7 @@ module Rubik
57
57
  cmd_meta[:handler].call(parsed.args, command_context)
58
58
  rescue Interrupt
59
59
  Rubik::REPL::InterruptHandler.restore_console_after_interrupt
60
- @output.puts "\n⚠️ [Rubik] Komut kullanıcı tarafından iptal edildi (^C)."
60
+ @output.puts "\n⚠️ [Rubik] Command cancelled by user (^C)."
61
61
  ensure
62
62
  # !goal dahil lifecycle komutları tracked dal ile aynı spinner
63
63
  # garantisini taşır (field incident 2026-10-12: !goal'ten kaçan
@@ -74,7 +74,7 @@ module Rubik
74
74
  rescue Interrupt
75
75
  cmd_interrupted = true
76
76
  Rubik::REPL::InterruptHandler.restore_console_after_interrupt
77
- @output.puts "\n⚠️ [Rubik] Komut kullanıcı tarafından iptal edildi (^C)."
77
+ @output.puts "\n⚠️ [Rubik] Command cancelled by user (^C)."
78
78
  ensure
79
79
  # A command (!plan/!goal) may leave a live spinner if it died mid-wait.
80
80
  kill_command_spinner!
@@ -99,7 +99,7 @@ module Rubik
99
99
  reap_dead_kernel_units! if respond_to?(:reap_dead_kernel_units!)
100
100
  else
101
101
  available = @commands.keys.sort.map { |c| "!#{c}" }.join(", ")
102
- @output.puts "Bilinmeyen komut: !#{parsed.command_name}. Kullanılabilir komutlar: #{available} (!help'e bakın)."
102
+ @output.puts "Unknown command: !#{parsed.command_name}. Available commands: #{available} (see !help)."
103
103
  end
104
104
  end
105
105
 
@@ -225,7 +225,7 @@ module Rubik
225
225
  return routed if routed[:provider]
226
226
 
227
227
  spec_str = routed[:spec].is_a?(Hash) ? "#{routed[:spec]['provider']}/#{routed[:spec]['name']}" : routed[:spec].to_s
228
- @output.puts "Hata: Model sağlayıcısı başlatılamadı (#{spec_str})."
228
+ @output.puts "Error: Could not initialize model provider (#{spec_str})."
229
229
  record_failed_turn!(text, "failed", "no LLM provider available (#{spec_str})", nil)
230
230
  nil
231
231
  end
@@ -314,28 +314,28 @@ module Rubik
314
314
  def drive_budget_continuations!(orchestrator, res)
315
315
  while !res[:ok] && res[:reason] == :budget_exhausted && Rubik::Storage::Layout.config_get(@config, "agent.ask_continue_on_limit", true)
316
316
  @output.puts "\n⚠️ [Rubik::Agent] #{res[:error]}"
317
- ans = ask_yes_no(" [Rubik::Agent] +20 adım ile devam edilsin mi?", default: "n")
317
+ ans = ask_yes_no(" [Rubik::Agent] Continue with +20 steps?", default: "n")
318
318
  break unless ["y", "yes", "evet"].include?(ans)
319
319
 
320
- @output.puts " [Rubik::Agent] Adım bütçesi +20 artırılıyor ve görev sürdürülüyor..."
320
+ @output.puts " [Rubik::Agent] Increasing step budget by +20 and resuming task..."
321
321
  res = orchestrator.continue_loop(20)
322
322
 
323
323
  end
324
324
  res
325
325
  end
326
326
 
327
- # Settle phase: merges the turn's tool history, then records and
328
- # reports the outcome (success render / incomplete report). theme and
329
- # md_enabled arrive from the display phase for the batch render.
327
+ # Settle phase: records the outcome FIRST, then merges the turn's tool
328
+ # history and reports the result. theme and md_enabled arrive from the
329
+ # display phase for the batch render.
330
330
  def settle_free_text_result!(text, res, orchestrator:, theme:, md_enabled:)
331
- # Plan 85 D-7 (kök neden): turn içi @history'deki tool ara adımlarını
332
- # conversation_history'ye kopyala — böylece continue'da model turn sırasındaki
333
- # bağlamı görür ve "sıfırdan keşfe" başlamaz. res[:loop_instance].history,
334
- # turn_result'ın döndürdüğü Loop örneğinin @history'sidir.
335
- merge_unseen_turn_tool_history!(res[:loop_instance])
336
-
337
331
  if res[:ok]
338
332
  record_turn_outcome!(text, res[:output].to_s, tokens: res[:tokens], streamed: res[:streamed] == true)
333
+ # Plan 85 D-7: copy in-turn tool steps into conversation_history so
334
+ # a follow-up sees them. This MUST follow record_turn_outcome! —
335
+ # its trim drops leading rows until a user row leads the window,
336
+ # so merging first evicts every tool row on a fresh/cleared window
337
+ # (issue #557). All rescue paths already use this ordering.
338
+ merge_unseen_turn_tool_history!(res[:loop_instance])
339
339
 
340
340
  # Only print the final answer when it was not already streamed
341
341
  # live; batch answers get full markdown rendering on capable TTYs.
@@ -356,8 +356,9 @@ module Rubik
356
356
  emit_turn_finished(kind: "success", prompt: text, outcome: res[:output].to_s,
357
357
  orchestrator: orchestrator, tokens: res[:tokens])
358
358
  else
359
- @output.puts "Görev tamamlanamadı: #{res[:error]}"
359
+ @output.puts "Task could not be completed: #{res[:error]}"
360
360
  record_failed_turn!(text, "incomplete", res[:error], orchestrator)
361
+ merge_unseen_turn_tool_history!(res[:loop_instance])
361
362
  end
362
363
  end
363
364
 
@@ -407,8 +408,8 @@ module Rubik
407
408
  # execute_steps yolu) işletilir — aynı @history, aynı adım bütçesi
408
409
  # (kullanıcının !steps extend'i dahil). Amaç-eşleşmesi BİREBİRDİR:
409
410
  # 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"
411
+ RESUME_INTENTS = ["devam et", "devam", "continue", "sürdür", "resume"].freeze
412
+ RESUME_PROMPT = "continue"
412
413
  RESUME_REASON = "llm_error_recovery"
413
414
 
414
415
  def resumable_turn? = !!@resumable_turn
@@ -443,14 +444,14 @@ module Rubik
443
444
  def stash_and_announce_resume!(orchestrator)
444
445
  return unless stash_resumable_turn!(orchestrator)
445
446
 
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."
447
+ @output.puts "[Rubik] Turn paused (step #{orchestrator.step_count}/#{orchestrator.max_steps}). " \
448
+ "Type 'continue' to resume with the same context and step budget; type anything else to run as a new task."
448
449
  end
449
450
 
450
451
  # Duraklatılmış turn'in yeniden koşusu: taze turn yaşam döngüsünü
451
452
  # (arming → display → settle → rescue merdiveni → ensure teardown)
452
453
  # 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
+ # recorder'a ve konuşma hafızasına "continue" olarak düşer — dürüst
454
455
  # provenance; orijinal görev metni Loop'un kendi @history'sinde
455
456
  # yaşamaya devam eder ve modele tekrar gönderilmez.
456
457
  def execute_resumed_turn!
@@ -498,7 +499,7 @@ module Rubik
498
499
  @recorder&.record("cancelled_turn",
499
500
  "question" => text.to_s.strip[0, 80],
500
501
  "reason" => "Interrupted by user (^C)")
501
- @output.puts "\n⚠️ [Rubik::Agent] Görev kullanıcı tarafından iptal edildi (^C)."
502
+ @output.puts "\n⚠️ [Rubik::Agent] Task cancelled by user (^C)."
502
503
  record_failed_turn!(text, "cancelled", "Interrupted by user (^C)", orchestrator)
503
504
  merge_failed_turn_tool_history!(orchestrator)
504
505
  end
@@ -510,7 +511,7 @@ module Rubik
510
511
  # LLM error. Sanitize before use.
511
512
  def handle_llm_client_error!(text, error, orchestrator)
512
513
  message = Rubik::Platform.safe_utf8(error.message)
513
- @output.puts "[Rubik::LLM Hatası] #{message}"
514
+ @output.puts "[Rubik::LLM Error] #{message}"
514
515
  record_failed_turn!(text, "failed", message, orchestrator)
515
516
  merge_failed_turn_tool_history!(orchestrator)
516
517
  stash_and_announce_resume!(orchestrator) unless @autonomous_turn
@@ -520,7 +521,7 @@ module Rubik
520
521
  # error path above.
521
522
  def handle_unexpected_error!(text, error, orchestrator)
522
523
  message = Rubik::Platform.safe_utf8(error.message)
523
- @output.puts "[Hata] #{error.class}: #{message}"
524
+ @output.puts "[Error] #{error.class}: #{message}"
524
525
  record_failed_turn!(text, "failed", "#{error.class}: #{message}", orchestrator)
525
526
  merge_failed_turn_tool_history!(orchestrator)
526
527
  end
@@ -575,15 +576,15 @@ module Rubik
575
576
  # interrupted WAIT; one with owned work is a cancelled TASK TREE — and
576
577
  # remaining work is named, so an incomplete cleanup is never silent.
577
578
  def task_cancellation_lines(outcome)
578
- return ["⏸️ [Rubik] Bekleme kesildi (^C) — iptal edilecek bağlı alt ajan yok."] unless outcome&.any?
579
+ return ["⏸️ [Rubik] Wait interrupted (^C) — no linked subagents to cancel."] unless outcome&.any?
579
580
 
580
- line = "🛑 [Rubik] Görev ağacı iptal edildi (^C): #{outcome.stopped.size} bağlı alt ajan durduruldu"
581
- line << ", #{outcome.queued_cancelled.size} kuyruk işi iptal edildi" unless outcome.queued_cancelled.empty?
581
+ line = "🛑 [Rubik] Task tree cancelled (^C): #{outcome.stopped.size} linked subagents stopped"
582
+ line << ", #{outcome.queued_cancelled.size} queued jobs cancelled" unless outcome.queued_cancelled.empty?
582
583
  if outcome.complete?
583
- line << "; temizlik tamamlandı."
584
+ line << "; cleanup completed."
584
585
  else
585
586
  remaining = outcome.remaining.map { |r| "#{r[:id]}:#{r[:state]}" }.join(", ")
586
- line << "; temizlik TAMAMLANMADI — kalan: #{remaining}."
587
+ line << "; cleanup INCOMPLETE — remaining: #{remaining}."
587
588
  end
588
589
  [line]
589
590
  end
@@ -26,6 +26,7 @@ module Rubik
26
26
  heredoc_delimiter = nil
27
27
  last_line_at = nil
28
28
  print_banner
29
+ maybe_offer_connect_wizard! if respond_to?(:maybe_offer_connect_wizard!)
29
30
  Rubik::REPL::InterruptHandler.with_handler do
30
31
  while @running
31
32
  result = read_and_process_line(multiline_buffer, heredoc_delimiter, last_line_at: last_line_at)
@@ -196,15 +197,20 @@ module Rubik
196
197
  end
197
198
 
198
199
  def process_normal_line(line, _multiline_buffer)
199
- # Only trigger heredoc if line explicitly opens a multiline block (e.g. `<<EOF`, `!plan <<EOF`)
200
- # NEVER trigger on inline operators like `array << item` or `a << b`
201
- heredoc_match = line.match(/\A[ \t]*(?:[a-zA-Z0-9_!.-]+[ \t]+)?<<[-~]?['"]?([A-Za-z0-9_]+)['"]?[ \t]*\z/)
200
+ # Only trigger heredoc if line explicitly opens a multiline block
201
+ # (e.g. `<< EOF`, `!plan << EOF`). Whitespace after `<<` is required:
202
+ # `array <<item` is an inline append operator, not a heredoc (#557).
203
+ heredoc_match = line.match(/\A[ \t]*(?:![a-zA-Z0-9_.-]+[ \t]+)?<<[-~]?[ \t]+['"]?([A-Za-z0-9_]+)['"]?[ \t]*\z/)
202
204
  if heredoc_match && !line.strip.start_with?("#")
203
205
  delimiter = heredoc_match[1]
204
- prefix = line.sub(/<<[-~]?['"]?#{Regexp.escape(delimiter)}['"]?\s*$/, "").strip
206
+ prefix = line.sub(/<<[-~]?[ \t]+['"]?#{Regexp.escape(delimiter)}['"]?\s*$/, "").strip
205
207
  buffer = prefix.empty? ? [] : [prefix]
206
208
  { stop: false, buffer: buffer, delimiter: delimiter }
207
209
  elsif ["exit", "quit", "!exit", "!quit"].include?(line.strip.downcase)
210
+ # Design note (#557): interactive mode stops the REPL here, while
211
+ # stream mode (execute_input) sends the same tokens to the model.
212
+ # This divergence is deliberate — piped scripts use the model as
213
+ # the interpreter — so do not "align" it without a product decision.
208
214
  stop
209
215
  { stop: true, buffer: [], delimiter: nil }
210
216
  else
@@ -4,6 +4,8 @@ require_relative "../events"
4
4
  require_relative "../log"
5
5
  require_relative "../platform"
6
6
  require_relative "../storage/layout"
7
+ require_relative "../ui/capability"
8
+ require_relative "../connect"
7
9
  require_relative "../orchestrator/subagent/notices"
8
10
  require_relative "../prompt/conversation_rows"
9
11
  require_relative "pending_notice_queue"
@@ -133,6 +135,42 @@ module Rubik
133
135
  resync_llm_route!
134
136
  end
135
137
 
138
+ # First-run onboarding: after the banner shows "model yapılandırılmamış",
139
+ # offer the connect wizard once when boot could not resolve an LLM
140
+ # client. Opt-in ask (default no — Confirmations#ask_yes_no collapses
141
+ # to the default off live TTYs, so scripted boots are untouched),
142
+ # knob-gated (connect.first_run_offer), once per process, never
143
+ # raises — the same boot-path honesty as sync_default_llm_route.
144
+ def maybe_offer_connect_wizard!
145
+ return if @connect_offer_shown
146
+
147
+ @connect_offer_shown = true
148
+ return unless @config && @output && @input
149
+ return unless respond_to?(:ask_yes_no)
150
+ return unless Rubik::UI::Capability.interactive?(input: @input, output: @output)
151
+ return unless Rubik::Storage::Layout.config_get(@config, "connect.first_run_offer", true)
152
+ return unless llm_client_pending?
153
+
154
+ answer = ask_yes_no("No LLM provider is configured yet. Run the connect wizard?", default: "n")
155
+ return unless ["y", "yes", "evet"].include?(answer.to_s.downcase)
156
+
157
+ ui = Rubik::Connect::PromptUI.new(input: @input,
158
+ output: Rubik::UI::Capability.unwrap_tee(@output) || @output,
159
+ theme: @ui_theme)
160
+ Rubik::Connect::Wizard.new(config: @config, ui: ui, io: @output, scope: :global,
161
+ refresh: -> { refresh_llm_registry! }).run
162
+ rescue StandardError => e
163
+ debug_warn("Connect wizard offer failed: #{e.class}: #{e.message}")
164
+ end
165
+
166
+ # True when boot's default route failed to satisfy the llm_client
167
+ # coeffect — the honest "nothing usable is configured" signal, so a
168
+ # locally-running Ollama user is never offered the wizard.
169
+ def llm_client_pending?
170
+ context = @runtime_manager&.context
171
+ context.respond_to?(:get) ? context.get(:llm_client).nil? : false
172
+ end
173
+
136
174
  # Live LLM re-route (reactive config wiring, !model/!provider switches):
137
175
  # re-open sticky routing so the next free-text turn re-resolves with the
138
176
  # new model (Plan 61 D-7), then re-provide the default llm_client
@@ -238,12 +238,18 @@ module Rubik
238
238
 
239
239
  def inject_subagent_notice_into_conversation_history!(notice)
240
240
  xml_payload = Rubik::Orchestrator::Subagent::Notices.history_block([notice])
241
- history = shell_state(:conversation_history)
242
- unless history
243
- history = []
244
- @shell.instance_variable_set(:@conversation_history, history)
241
+ # The bus thread injects while the turn thread may replace the whole
242
+ # history array in trim_conversation_window!. Share the standby mutex
243
+ # with that mutation so a notice is never written to a stale array
244
+ # (issue #557).
245
+ subagent_notices_mutex.synchronize do
246
+ history = shell_state(:conversation_history)
247
+ unless history
248
+ history = []
249
+ @shell.instance_variable_set(:@conversation_history, history)
250
+ end
251
+ Rubik::Prompt::ConversationRows.append_notice!(history, xml_payload)
245
252
  end
246
- Rubik::Prompt::ConversationRows.append_notice!(history, xml_payload)
247
253
  end
248
254
 
249
255
  def flush_subagent_notices!
@@ -66,7 +66,7 @@ module Rubik
66
66
  # Plan 109: koleksiyon with_collecting içinde — reaktif bir uyandırma
67
67
  # Enter'ı yapıştırılan metne boş satır eklemez.
68
68
  def read_paste_block
69
- @output.puts "[Rubik] Paste modu: metni yapıştırın, bitirmek için tek başına '.' yazın (Ctrl+C iptal)."
69
+ @output.puts "[Rubik] Paste mode: paste the text, type '.' on its own to finish (Ctrl+C to cancel)."
70
70
  lines = []
71
71
  collector = lambda do
72
72
  loop do
@@ -11,7 +11,7 @@ module Rubik
11
11
  # effects and is pruned from its parent on every exit.
12
12
  class PromptGrace
13
13
  ESCAPE_TIMEOUT = 0.03
14
- STATUS = "Gönderiliyor… Esc: düzenlemeye dön"
14
+ STATUS = "Sending… Esc: return to editing"
15
15
 
16
16
  def initialize(input:, output:, context: nil, clock: nil, reader: nil)
17
17
  @input = input
@@ -42,7 +42,7 @@ module Rubik
42
42
  # the last processed key. Do not let its Enter submit a later turn.
43
43
  if @input.respond_to?(:nread) && @input.nread.positive?
44
44
  @input.iflush
45
- @output.print "\a\r\e[2K[Rubik] Bekleme sırasında gelen tuşlar yok sayıldı.\r\n"
45
+ @output.print "\a\r\e[2K[Rubik] Keys received while waiting were ignored.\r\n"
46
46
  end
47
47
  return :execute
48
48
  end
@@ -58,7 +58,7 @@ module Rubik
58
58
 
59
59
  # Other keys are intentionally rejected, with immediate feedback.
60
60
  # Enter never leaks into the next readline as an accidental submit.
61
- @output.print "\a\r\e[2K#{STATUS} · Tuş yok sayıldı"
61
+ @output.print "\a\r\e[2K#{STATUS} · Key ignored"
62
62
  @output.flush
63
63
  end
64
64
  rescue Interrupt
@@ -193,7 +193,12 @@ module Rubik
193
193
  # @return [void]
194
194
  def execute_input(input_text)
195
195
  parsed = CommandParser.parse(input_text)
196
- @recorder.record(parsed.type, input_text) if !@replaying && parsed.type != :empty && parsed.type != :prompt
196
+ # Redact at the record seam, BEFORE the transcript write: provider
197
+ # CLI forms (`--key=…`, `set <name> key <value>`) are accepted here and
198
+ # must never land in the JSONL even if a recorder wrapper changes
199
+ # (issue #542). The recorder masks again as defence in depth.
200
+ clean_input = Rubik::Security::Redactor.redact(input_text)
201
+ @recorder.record(parsed.type, clean_input) if !@replaying && parsed.type != :empty && parsed.type != :prompt
197
202
 
198
203
  case parsed.type
199
204
  when :empty
@@ -208,7 +213,10 @@ module Rubik
208
213
  if resume_intent?(parsed.raw)
209
214
  execute_resumed_turn!
210
215
  else
211
- execute_free_text(parsed.raw)
216
+ # The redacted form is the one that reaches the recorder, the
217
+ # conversation window and every downstream LLM request — a
218
+ # pasted credential must not become durable prompt memory (#542).
219
+ execute_free_text(clean_input)
212
220
  end
213
221
  end
214
222
 
@@ -135,9 +135,20 @@ module Rubik
135
135
  Rubik::Platform.debug_warn("input ceiling lookup failed (#{e.class}: #{e.message}); using nil budget")
136
136
  nil
137
137
  end
138
- @conversation_history = Rubik::Prompt::ContextCompactor.trim_history_to_budget(
139
- @conversation_history, ceiling: ceiling, max_entries: MAX_CONVERSATION_ENTRIES
140
- )
138
+ # Serialize the read-compute-replace of the history array with the
139
+ # bus-thread notice injection (issue #557). Both sides use the same
140
+ # mutex owned by NoticeRouter; bare EmitHost doubles skip the lock.
141
+ if respond_to?(:notice_router)
142
+ notice_router.subagent_notices_mutex.synchronize do
143
+ @conversation_history = Rubik::Prompt::ContextCompactor.trim_history_to_budget(
144
+ @conversation_history, ceiling: ceiling, max_entries: MAX_CONVERSATION_ENTRIES
145
+ )
146
+ end
147
+ else
148
+ @conversation_history = Rubik::Prompt::ContextCompactor.trim_history_to_budget(
149
+ @conversation_history, ceiling: ceiling, max_entries: MAX_CONVERSATION_ENTRIES
150
+ )
151
+ end
141
152
  rescue StandardError => e
142
153
  Rubik::Log.warn(:repl, "conversation trim failed (#{e.class}: #{e.message}); window may exceed token budget")
143
154
  nil
@@ -46,12 +46,14 @@ module Rubik
46
46
  inverse = cleanup_fn || block
47
47
  return unless inverse
48
48
 
49
+ # Resolve dmesg before the monitor: walking to the parent while held is a child→parent inversion (#552).
50
+ dmesg = disposed? ? resolve_dmesg : nil
49
51
  @monitor.synchronize do
50
52
  if @disposed
51
53
  # Ω is sealed: the context is already torn down, so there is no
52
54
  # later drain that would run this inverse. Execute it now instead
53
55
  # of silently storing it in a dead accumulator (leaked cleanup).
54
- run_inverse(inverse)
56
+ run_inverse(inverse, dmesg: dmesg)
55
57
  else
56
58
  @disposables << inverse
57
59
  end
@@ -231,8 +233,7 @@ module Rubik
231
233
  # Resolve dmesg outside monitor to preserve parent→child lock order (F3).
232
234
  dmesg = resolve_dmesg
233
235
  parent = nil
234
- deferred_interrupt = nil
235
- @monitor.synchronize do
236
+ children, inverses = @monitor.synchronize do
236
237
  return if @disposed
237
238
 
238
239
  @disposed = true
@@ -246,12 +247,24 @@ module Rubik
246
247
  # "beginning" log reports).
247
248
  dmesg&.log(:context, :info, "Beginning context dispose with #{@disposables.size} inverse(s)")
248
249
 
249
- deferred_interrupt = dispose_children
250
- drained, drain_signal = drain_inverses(dmesg: dmesg)
251
- deferred_interrupt ||= drain_signal
250
+ # Detach under the monitor, then drain UNLOCKED so a teardown inverse may re-enter this context (#552).
251
+ detached = [@children.dup, @disposables.dup]
252
+ @children.clear
253
+ @disposables.clear
254
+ detached
255
+ end
256
+
257
+ deferred_interrupt = dispose_children(children)
258
+ drained, drain_signal = drain_inverses(inverses, dmesg: dmesg)
259
+ deferred_interrupt ||= drain_signal
252
260
 
253
- dmesg&.log(:context, :info, "Context dispose complete; #{drained} inverse(s) executed")
261
+ @monitor.synchronize do
262
+ @services.clear
263
+ @service_inverses.clear
264
+ @child_inverses.clear
254
265
  end
266
+
267
+ dmesg&.log(:context, :info, "Context dispose complete; #{drained} inverse(s) executed")
255
268
  # Release the child's monitor before reaching the parent (lock
256
269
  # order), then prune the parent's record of this child.
257
270
  parent&.prune_child(self)
@@ -271,15 +284,14 @@ module Rubik
271
284
  # so the descending iteration never observes mutation. A child's
272
285
  # deferred Interrupt/SystemExit is adopted as (possibly) the FIRST
273
286
  # signal of this cascade; returns the first deferred child signal.
274
- def dispose_children
287
+ def dispose_children(children)
275
288
  deferred = nil
276
- @children.reverse_each do |child|
289
+ children.reverse_each do |child|
277
290
  child.dispose unless child.disposed?
278
291
  rescue Interrupt, SystemExit => e
279
292
  record_deferred_signal(e)
280
293
  deferred ||= e
281
294
  end
282
- @children.clear
283
295
  deferred
284
296
  end
285
297
 
@@ -291,23 +303,17 @@ module Rubik
291
303
  # by dispose after bookkeeping and the parent prune. Late registration
292
304
  # racing the drain is monitor-serialized (pop loop, or the sealed
293
305
  # immediate-run path). Returns [drained, first_signal].
294
- def drain_inverses(dmesg:)
306
+ def drain_inverses(inverses, dmesg:)
295
307
  drained = 0
296
308
  deferred = nil
297
- begin
298
- while (inverse = @disposables.pop)
299
- begin
300
- run_inverse(inverse, dmesg: dmesg)
301
- drained += 1
302
- rescue Interrupt, SystemExit => e
303
- record_deferred_signal(e)
304
- deferred ||= e
305
- end
309
+ while (inverse = inverses.pop)
310
+ begin
311
+ run_inverse(inverse, dmesg: dmesg)
312
+ drained += 1
313
+ rescue Interrupt, SystemExit => e
314
+ record_deferred_signal(e)
315
+ deferred ||= e
306
316
  end
307
- ensure
308
- @services.clear
309
- @service_inverses.clear
310
- @child_inverses.clear
311
317
  end
312
318
  [drained, deferred]
313
319
  end
@@ -320,7 +326,7 @@ module Rubik
320
326
  end
321
327
 
322
328
  def record_deferred_signal(exception)
323
- @last_dispose_errors << exception
329
+ @monitor.synchronize { @last_dispose_errors << exception }
324
330
  Rubik::Log.warn(:runtime, "dispose inverse raised #{exception.class} (deferred until drain completes): #{exception.message}")
325
331
  end
326
332
 
@@ -333,9 +339,9 @@ module Rubik
333
339
  def run_inverse(inverse, dmesg: nil)
334
340
  inverse.call
335
341
  rescue StandardError => e
336
- @last_dispose_errors << e
342
+ @monitor.synchronize { @last_dispose_errors << e }
337
343
  Rubik::Log.warn(:runtime, "dispose inverse failed: #{e.class}: #{e.message}")
338
- dmesg ||= resolve_dmesg
344
+ # dmesg is pre-resolved by the caller; resolving here would re-walk the parent (#552).
339
345
  dmesg&.log(:context, :err, "Dispose inverse failed: #{e.class}: #{e.message}")
340
346
  end
341
347
  end
@@ -72,13 +72,16 @@ module Rubik
72
72
  end
73
73
 
74
74
  def unregister_component(name)
75
- @monitor.synchronize do
76
- name_str = name.to_s
77
- fiber = @fibers.delete(name_str)
78
- @fiber_deps.delete(name_str)
79
- @retry_gate.clear(name_str) # fresh-eye R2: disposed fibers must not leak their retry budget
80
- fiber&.dispose!
81
- end
75
+ name_str = name.to_s
76
+ fiber = detach_fiber(name_str)
77
+ return unless fiber
78
+ return if @monitor.synchronize { @fibers[name_str].equal?(fiber) }
79
+
80
+ fiber.dispose!
81
+ nil
82
+ rescue StandardError => e
83
+ Rubik::Log.warn(:runtime, "fiber '#{fiber&.name}' dispose failed: #{e.class}: #{e.message}")
84
+ nil
82
85
  end
83
86
 
84
87
  # Reactive retraction (AGENTS.md §5, Finding B): unlike Context#unprovide
@@ -111,15 +114,11 @@ module Rubik
111
114
  reconcile_all(changed_service: service_name)
112
115
  end
113
116
 
114
- # Reentrant lock safety: Monitor#synchronize is explicitly reentrant (recursive),
115
- # allowing swap_component to safely invoke unregister_component and register_component
116
- # from within the same thread without deadlocking.
117
+ # Detach under the monitor; tear down outside it so a factory inverse cannot invert the lock order.
117
118
  def swap_component(name, inject: [], requires: [], provides: [], config: {}, &new_factory)
118
- @monitor.synchronize do
119
- name_str = name.to_s
120
- unregister_component(name_str)
121
- register_component(name_str, inject: inject, requires: requires, provides: provides, config: config, &new_factory)
122
- end
119
+ name_str = name.to_s
120
+ unregister_component(name_str)
121
+ register_component(name_str, inject: inject, requires: requires, provides: provides, config: config, &new_factory)
123
122
  end
124
123
 
125
124
  def reconcile_all(changed_service: nil)
@@ -227,6 +226,15 @@ module Rubik
227
226
 
228
227
  private
229
228
 
229
+ # Detach a fiber + bookkeeping under the monitor; teardown is deferred.
230
+ def detach_fiber(name_str)
231
+ @monitor.synchronize do
232
+ @fiber_deps.delete(name_str)
233
+ @retry_gate.clear(name_str)
234
+ @fibers.delete(name_str)
235
+ end
236
+ end
237
+
230
238
  # Marks the fiber while its factory runs so nested reconciles skip it;
231
239
  # ensure-based so a raising factory (→ :failed) never wedges the marker.
232
240
  def with_activation_marker(fiber)