rubik 0.13.0 → 0.15.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 (131) hide show
  1. checksums.yaml +4 -4
  2. data/ATTRIBUTION.md +1 -1
  3. data/CHANGELOG.md +122 -1
  4. data/lib/rubik/adapter/node.rb +4 -1
  5. data/lib/rubik/ast/c_extractor.rb +1 -1
  6. data/lib/rubik/ast/fallback_cleaner.rb +6 -1
  7. data/lib/rubik/ast/graph.rb +38 -57
  8. data/lib/rubik/ast/graph_extensions.rb +57 -15
  9. data/lib/rubik/ast/ruby_extractor.rb +16 -6
  10. data/lib/rubik/ast/treesitter/c_walker.rb +11 -3
  11. data/lib/rubik/buffer/manager.rb +38 -11
  12. data/lib/rubik/buffer/snapshot.rb +116 -28
  13. data/lib/rubik/cli/connect.rb +3 -5
  14. data/lib/rubik/config/defaults.rb +3 -7
  15. data/lib/rubik/config/env_guard.rb +43 -0
  16. data/lib/rubik/config/schema.rb +7 -1
  17. data/lib/rubik/config/scoped.rb +12 -5
  18. data/lib/rubik/config/secret_policy.rb +6 -5
  19. data/lib/rubik/config.rb +1 -1
  20. data/lib/rubik/connect/models_dev.rb +11 -0
  21. data/lib/rubik/connect/probes.rb +9 -2
  22. data/lib/rubik/connect/wizard.rb +117 -57
  23. data/lib/rubik/context/repo_context_reader.rb +8 -4
  24. data/lib/rubik/diagnostics/collector.rb +25 -2
  25. data/lib/rubik/llm/chunk_assembler.rb +12 -1
  26. data/lib/rubik/llm/client.rb +19 -0
  27. data/lib/rubik/llm/connection_pool.rb +7 -1
  28. data/lib/rubik/llm/formatter.rb +22 -2
  29. data/lib/rubik/llm/provider_key.rb +32 -0
  30. data/lib/rubik/llm/registry.rb +18 -2
  31. data/lib/rubik/llm/router.rb +27 -1
  32. data/lib/rubik/llm/session_header.rb +128 -0
  33. data/lib/rubik/llm/sse_parser.rb +57 -10
  34. data/lib/rubik/lsp/client.rb +244 -23
  35. data/lib/rubik/lsp/document_store.rb +6 -0
  36. data/lib/rubik/lsp/manager.rb +14 -0
  37. data/lib/rubik/lsp/transport.rb +34 -7
  38. data/lib/rubik/mcp/transport/stdio.rb +42 -4
  39. data/lib/rubik/orchestrator/continuation_manager.rb +68 -7
  40. data/lib/rubik/orchestrator/goal_ledger/ledger.rb +18 -2
  41. data/lib/rubik/orchestrator/goal_ledger/observation_projection.rb +13 -4
  42. data/lib/rubik/orchestrator/goal_ledger/validator.rb +46 -7
  43. data/lib/rubik/orchestrator/goal_ledger/verifier.rb +8 -1
  44. data/lib/rubik/orchestrator/goal_session.rb +14 -14
  45. data/lib/rubik/orchestrator/goal_wait.rb +15 -9
  46. data/lib/rubik/orchestrator/loop.rb +39 -39
  47. data/lib/rubik/orchestrator/provider_resolver.rb +29 -6
  48. data/lib/rubik/orchestrator/step_executor.rb +17 -2
  49. data/lib/rubik/orchestrator/subagent/instance.rb +46 -5
  50. data/lib/rubik/orchestrator/subagent/lifecycle.rb +25 -25
  51. data/lib/rubik/orchestrator/subagent/messaging.rb +5 -1
  52. data/lib/rubik/orchestrator/subagent/narration.rb +2 -1
  53. data/lib/rubik/orchestrator/subagent/notices.rb +7 -3
  54. data/lib/rubik/orchestrator/subagent/questioner.rb +42 -4
  55. data/lib/rubik/orchestrator/subagent/reaper.rb +70 -20
  56. data/lib/rubik/orchestrator/subagent/start_gate.rb +1 -1
  57. data/lib/rubik/orchestrator/subagent/step_runner.rb +7 -7
  58. data/lib/rubik/orchestrator/subagent/supervisor.rb +21 -3
  59. data/lib/rubik/orchestrator/tool_call_id.rb +8 -4
  60. data/lib/rubik/orchestrator/turn_executor/subagent_channel.rb +21 -5
  61. data/lib/rubik/orchestrator/turn_executor/user_channel.rb +40 -5
  62. data/lib/rubik/orchestrator/turn_executor.rb +24 -8
  63. data/lib/rubik/platform/filesystem.rb +52 -24
  64. data/lib/rubik/platform/process.rb +32 -7
  65. data/lib/rubik/platform/sanitize.rb +17 -18
  66. data/lib/rubik/platform.rb +27 -0
  67. data/lib/rubik/plugin/storage.rb +34 -8
  68. data/lib/rubik/prompt/context_builder.rb +2 -1
  69. data/lib/rubik/prompt/doctrine.rb +3 -2
  70. data/lib/rubik/repair/loop.rb +22 -2
  71. data/lib/rubik/repl/commands/agent_context.rb +1 -1
  72. data/lib/rubik/repl/commands/agent_execution.rb +20 -15
  73. data/lib/rubik/repl/commands/base.rb +7 -3
  74. data/lib/rubik/repl/commands/buffer.rb +21 -2
  75. data/lib/rubik/repl/commands/connect.rb +0 -1
  76. data/lib/rubik/repl/commands/lsp.rb +1 -1
  77. data/lib/rubik/repl/commands/plugins.rb +31 -31
  78. data/lib/rubik/repl/commands/session.rb +16 -6
  79. data/lib/rubik/repl/commands/workspace.rb +4 -4
  80. data/lib/rubik/repl/input_execution.rb +33 -32
  81. data/lib/rubik/repl/input_loop.rb +9 -4
  82. data/lib/rubik/repl/lifecycle.rb +1 -2
  83. data/lib/rubik/repl/notice_router.rb +11 -5
  84. data/lib/rubik/repl/paste_support.rb +1 -1
  85. data/lib/rubik/repl/prompt_grace.rb +3 -3
  86. data/lib/rubik/repl/service_catalog.rb +6 -2
  87. data/lib/rubik/repl/shell.rb +10 -2
  88. data/lib/rubik/repl/turn_recorder.rb +18 -4
  89. data/lib/rubik/runtime/context.rb +33 -27
  90. data/lib/rubik/runtime/manager.rb +23 -15
  91. data/lib/rubik/runtime/manifest_store.rb +7 -2
  92. data/lib/rubik/runtime/task_manager.rb +13 -10
  93. data/lib/rubik/sandbox/driver/base.rb +34 -0
  94. data/lib/rubik/sandbox/driver/bubblewrap.rb +60 -8
  95. data/lib/rubik/sandbox/driver/docker.rb +8 -0
  96. data/lib/rubik/sandbox/driver/podman.rb +8 -0
  97. data/lib/rubik/sandbox/driver/process.rb +29 -1
  98. data/lib/rubik/sandbox/runner.rb +9 -1
  99. data/lib/rubik/security/classifier/classifier.rb +147 -13
  100. data/lib/rubik/security/classifier/commands/docker.yaml +1 -1
  101. data/lib/rubik/security/classifier/commands/git.yaml +27 -1
  102. data/lib/rubik/security/classifier/commands/sed.yaml +3 -3
  103. data/lib/rubik/security/classifier/database.rb +2 -2
  104. data/lib/rubik/security/command_gate.rb +8 -1
  105. data/lib/rubik/security/path_policy.rb +28 -3
  106. data/lib/rubik/security/redactor.rb +62 -19
  107. data/lib/rubik/session/recorder.rb +27 -20
  108. data/lib/rubik/session/replayer.rb +29 -7
  109. data/lib/rubik/storage/store.rb +26 -5
  110. data/lib/rubik/tools/builtins/exec.rb +8 -2
  111. data/lib/rubik/tools/builtins/files.rb +8 -12
  112. data/lib/rubik/tools/builtins/grep.rb +3 -2
  113. data/lib/rubik/tools/builtins/interactive.rb +5 -2
  114. data/lib/rubik/tools/builtins/lsp.rb +59 -9
  115. data/lib/rubik/tools/builtins/send_message.rb +7 -2
  116. data/lib/rubik/tools/builtins/show_file.rb +1 -1
  117. data/lib/rubik/tools/builtins/synthesis.rb +4 -4
  118. data/lib/rubik/tools/preflight_runner.rb +4 -1
  119. data/lib/rubik/tools/result_normalizer.rb +1 -1
  120. data/lib/rubik/ui/banner.rb +3 -3
  121. data/lib/rubik/ui/dialog.rb +15 -8
  122. data/lib/rubik/ui/diff_viewer.rb +4 -4
  123. data/lib/rubik/ui/frame.rb +13 -3
  124. data/lib/rubik/ui/markdown_stream.rb +8 -2
  125. data/lib/rubik/ui/panel.rb +11 -11
  126. data/lib/rubik/ui/renderer.rb +10 -7
  127. data/lib/rubik/ui/spinner.rb +1 -1
  128. data/lib/rubik/ui/statusline.rb +3 -3
  129. data/lib/rubik/ui/theme.rb +1 -1
  130. data/lib/rubik/version.rb +1 -1
  131. metadata +4 -1
@@ -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"
@@ -25,13 +26,11 @@ module Rubik
25
26
  class Loop
26
27
  attr_accessor :history, :invalid_tool_count, :last_turn_streamed, :context_warning_emitted, :loop_context
27
28
  attr_reader :max_steps, :step_count, :model, :total_tokens, :warn_at_ratio, :runtime_manager, :context_limit, :max_output_tokens, :config
28
- # Collaborator-facing state (Plan 54 D-5): loop state physically stays on Loop;
29
- # extracted collaborators reach it through these accessors.
29
+ # Collaborator-facing state (Plan 54 D-5): loop state stays on Loop; collaborators reach it via these accessors.
30
30
  attr_reader :provider, :on_step, :tool_registry, :shell, :buffer_manager, :lsp_manager, :step_executor,
31
31
  :budget_manager, :stream_manager, :activity
32
32
 
33
- # Channel-owned counter (TurnExecutor::NudgePolicy); the public reader
34
- # name is load-bearing (tests, REPL surfaces).
33
+ # Channel-owned counter (TurnExecutor::NudgePolicy); public reader name is load-bearing.
35
34
  def empty_response_count = turn_executor.nudge_policy.count
36
35
 
37
36
  def initialize(provider:, tool_registry:, max_steps: 40, warn_at_ratio: 0.75, model: nil, on_step: nil, shell: nil, context_limit: nil,
@@ -49,8 +48,6 @@ module Rubik
49
48
  # in between would make prompt and execution disagree.
50
49
  @shell = shell
51
50
  @buffer_manager = shell&.buffer_manager
52
- @snapshot_store = shell&.snapshot_store
53
- @context_index = shell&.context_index
54
51
  @lsp_manager = shell&.lsp_manager
55
52
  @config = shell&.config
56
53
  @root_dir = File.expand_path(shell&.buffer_manager&.root_dir || Dir.pwd)
@@ -178,27 +175,32 @@ module Rubik
178
175
  end
179
176
  end
180
177
 
181
- # auto: unattended auto-extension (!goal auto-continue) — the model
182
- # sees an honest notice instead of a "User approved" claim no user made.
178
+ # auto: unattended auto-extension (!goal auto-continue) — an honest notice, not a fake "User approved".
183
179
  def continue_loop(extra_steps = 20, plan_only: false, auto: false)
184
- # Retention seam — see SubagentNoticeInbox#keep_for_continuation.
185
- subagent_notice_inbox.keep_for_continuation
186
- extend_budget(extra_steps)
187
- target_model = @model
188
- opts = target_model ? { model: target_model } : {}
189
- opts[:tools] = @tool_registry.schemas
190
-
191
- # Plan 61 D-14: notifications travel as their own user message —
192
- # appending to @history.last may target a tool result or a
193
- # content-less assistant message, which provider formatters then
194
- # mangle.
195
- approval = auto ? "Step budget auto-extended (unattended continuation, agent.goal_auto_continue_limit)." : "User approved extending step budget by #{extra_steps} steps."
196
- continuation_msg = "<step_budget_extended extra=\"#{extra_steps}\" new_max=\"#{@max_steps}\" " \
197
- "current=\"#{@step_count}\" auto=\"#{auto}\" " \
198
- "message=\"#{approval} " \
199
- "Continue working toward completion.\" />"
200
- @history << { role: "user", content: continuation_msg }
201
- execute_steps(opts: opts, plan_only: plan_only)
180
+ # run()'ın ensure'i eski alt bağlamı imha etti; resume_turn! ile aynı
181
+ # disiplin (issue #595-3, §C): bayat bağlamı imha et, taze ctx.extend
182
+ # kur, koşu sonunda imha et — yoksa her devam ölü çocuk sızdırır.
183
+ @loop_context&.dispose
184
+ @loop_context = @runtime_manager&.context&.extend
185
+ begin
186
+ subagent_notice_inbox.keep_for_continuation # retention seam: SubagentNoticeInbox#keep_for_continuation
187
+ extend_budget(extra_steps)
188
+ target_model = @model
189
+ opts = target_model ? { model: target_model } : {}
190
+ opts[:tools] = @tool_registry.schemas
191
+
192
+ # Plan 61 D-14: notifications travel as their own user message — appending to
193
+ # @history.last may target a tool/tool-less row that formatters mangle.
194
+ approval = auto ? "Step budget auto-extended (unattended continuation, agent.goal_auto_continue_limit)." : "User approved extending step budget by #{extra_steps} steps."
195
+ continuation_msg = "<step_budget_extended extra=\"#{extra_steps}\" new_max=\"#{@max_steps}\" " \
196
+ "current=\"#{@step_count}\" auto=\"#{auto}\" " \
197
+ "message=\"#{approval} " \
198
+ "Continue working toward completion.\" />"
199
+ @history << { role: "user", content: continuation_msg }
200
+ execute_steps(opts: opts, plan_only: plan_only)
201
+ ensure
202
+ @loop_context&.dispose
203
+ end
202
204
  end
203
205
 
204
206
  # ── !goal resume (issue #106) ─────────────────────────────────────
@@ -318,8 +320,8 @@ module Rubik
318
320
  )
319
321
  end
320
322
 
321
- # Lightweight fingerprint of environment factors that affect the rendered system prompt.
322
- # Preserves prompt caching by avoiding regeneration when state is unchanged.
323
+ # Fingerprint of the environment factors affecting the rendered system
324
+ # prompt — avoids regeneration (keeps prompt caching) while unchanged.
323
325
  def prompt_state_fingerprint(plan_only: false)
324
326
  tools = plan_only ? [] : (@tool_registry&.schemas&.map { |s| s[:name] || s["name"] } || [])
325
327
  skills = Rubik::Coeffects.get(@runtime_manager&.context, Rubik::Coeffects::SKILL_MANAGER)&.prompt_index
@@ -330,8 +332,8 @@ module Rubik
330
332
  [tools, skills, subagents, dirty, lsp_diags].hash
331
333
  end
332
334
 
333
- # Dynamically updates @history[0] in-place if tools, skills, subagents, dirty files or LSP
334
- # change mid-execution. Keeps prompt cache intact on zero-change steps.
335
+ # Updates @history[0] in-place when tools, skills, subagents, dirty files
336
+ # or LSP change mid-execution; keeps the prompt cache intact on no-change.
335
337
  def refresh_system_prompt_if_needed!(mode:, plan_only:, extra_context: nil)
336
338
  return unless @history&.first && Prompt::ConversationRows.role_of(@history.first) == "system"
337
339
  return if (current_fp = prompt_state_fingerprint(plan_only: plan_only)) == @last_prompt_fingerprint
@@ -471,15 +473,13 @@ module Rubik
471
473
  effective_opts[:timeout] ||= effective_opts[:stream_timeout]
472
474
  # llm.* retry knobs join the timeout bridge above (per-call opts win).
473
475
  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
476
+ provider_resolver.apply_reasoning_knobs(effective_opts)
477
+ # Per-provider session header (opencode-style hard-400 gateways): one
478
+ # call before the stream/batch branch covers both wire exits; the
479
+ # identity is the shell coeffect (same anchor as the subagent lane).
480
+ provider_resolver.apply_session_header!(
481
+ effective_opts, Rubik::LLM::SessionHeader.session_key_from_context(@runtime_manager&.context)
482
+ )
483
483
 
484
484
  if streaming_enabled && @provider.respond_to?(:stream_chat)
485
485
  @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,9 +111,11 @@ 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
118
+ @pending_question_id = nil
117
119
  end
118
120
 
119
121
  def uptime = @started_at ? ((@ended_at || Time.now) - @started_at).to_f : 0.0
@@ -148,12 +150,29 @@ module Rubik
148
150
  # Inbox girdisi: mesaj metni + GERÇEK gönderen id'si. nil veya makine
149
151
  # adı "agent-0" gönderenler render'da maestro persona'sına çevrilir
150
152
  # (iki-düzlem adlandırma sözleşmesi) — subagent gönderenler kendi
151
- # id'leriyle görünür (drain: StepRunner#sender_label).
152
- InboxMessage = Struct.new(:text, :from)
153
+ # id'leriyle görünür (drain: StepRunner#sender_label). `answer`
154
+ # bayrağı (issue #595-4): push anında instance :waiting_input'taysa
155
+ # VE `in_reply_to` bekleyen sorunun id'siyle eşleşiyorsa mesaj bir
156
+ # ask_question CEVABI olarak etiketlenir — questioner yalnız eşleşen
157
+ # mesajı cevap olarak tüketir; eşleşmeyenler (soru penceresinde gelen
158
+ # steering dahil) inbox'a geri konur ve drain ile normal mesaj
159
+ # satırı olarak history'ye gider (#595-4 follow-up).
160
+ InboxMessage = Struct.new(:text, :from, :answer, :in_reply_to)
161
+
162
+ # The currently open ask_question id (nil outside a :waiting_input
163
+ # window). Questioner opens/closes it around the question; senders
164
+ # pair their reply against it via send_message(in_reply_to: ...).
165
+ def pending_question_id
166
+ @monitor.synchronize { @pending_question_id }
167
+ end
153
168
 
154
- def post_message(message, sender: nil, additional_steps: nil)
169
+ def post_message(message, sender: nil, additional_steps: nil, in_reply_to: nil)
155
170
  @monitor.synchronize do
156
- @inbox.push(InboxMessage.new(message, sender))
171
+ # Answer pairing (#595-4 follow-up): only a reply that echoes the
172
+ # id of the question currently waiting poses as the answer — a
173
+ # bare steering message pushed mid-window stays untagged.
174
+ answer = awaiting_human? && !in_reply_to.to_s.empty? && in_reply_to == @pending_question_id
175
+ @inbox.push(InboxMessage.new(message, sender, answer, in_reply_to))
157
176
  if error_paused?
158
177
  resume!(additional_steps: additional_steps)
159
178
  elsif awaiting_budget? || additional_steps
@@ -252,6 +271,15 @@ module Rubik
252
271
  end
253
272
  end
254
273
 
274
+ # Deadline for the budget-exhausted park, mirroring error_wait_timeout
275
+ # (issue #553). A non-positive configured value falls back to the
276
+ # resilience default so a parked worker can never wait unbounded.
277
+ def budget_exhausted_ttl
278
+ raw = Rubik::Storage::Layout.config_get(@config, "subagents.error_wait_timeout", nil)
279
+ ttl = raw.nil? ? Resilience::DEFAULT_ERROR_WAIT_TIMEOUT : raw.to_f
280
+ ttl.positive? ? ttl : Resilience::DEFAULT_ERROR_WAIT_TIMEOUT
281
+ end
282
+
255
283
  def pause_and_await_budget_expansion!(wait_timeout = nil)
256
284
  timeout = wait_timeout || Rubik::Storage::Layout.config_get(@config, "subagents.budget_wait_timeout", 180) || 180
257
285
  payload = nil
@@ -283,7 +311,20 @@ module Rubik
283
311
  Notices.emit(@event_bus, Notices::COMPLETED_EVENT, exhausted_payload) if exhausted_payload
284
312
 
285
313
  @monitor.synchronize do
286
- @budget_cond.wait while @state == :budget_exhausted
314
+ # Bounded parked pool (#553): an exhausted worker used to wait with
315
+ # NO deadline. While parked, active? excluded it from concurrency
316
+ # accounting and terminal_and_settled? excluded it from reaping, so
317
+ # an unanswered grant request leaked a live thread forever. Mirror
318
+ # the error-pause expiry: after error_wait_timeout with no grant,
319
+ # fail the run so it becomes terminal and reapable.
320
+ exhausted_ttl = budget_exhausted_ttl
321
+ @budget_cond.wait(exhausted_ttl) if @state == :budget_exhausted
322
+ if @state == :budget_exhausted
323
+ transition!(:failed)
324
+ @last_error ||= "Budget exhausted and no grant arrived within #{exhausted_ttl}s"
325
+ @unit&.sync_state!
326
+ return false
327
+ end
287
328
  return false if terminal?
288
329
 
289
330
  transition!(:running)
@@ -5,14 +5,12 @@ require_relative "../../errors"
5
5
  module Rubik
6
6
  module Orchestrator
7
7
  module Subagent
8
- # The Instance lifecycle vocabulary, extracted from instance.rb to
9
- # satisfy module hygiene (same vertical-cohesion extraction as
10
- # StepRunner/Questioner, Plan 95): TRANSITIONS is the single home of
11
- # the state machine, transition! its only mutation path, and these
12
- # predicates the only control-flow surface. Instance includes this
13
- # module, so Instance::TRANSITIONS / Instance::StateError remain the
14
- # public constants — adding a state means editing THIS file (plus the
15
- # kernel STATE_MAP, held by contract test).
8
+ # The Instance lifecycle vocabulary (Plan 95 extraction): TRANSITIONS
9
+ # is the single home of the state machine, transition! its only
10
+ # mutation path, these predicates the only control-flow surface.
11
+ # Instance::TRANSITIONS / Instance::StateError stay the public
12
+ # constants — adding a state means editing THIS file (plus the kernel
13
+ # STATE_MAP, held by contract test).
16
14
  module Lifecycle
17
15
  class StateError < Rubik::StateError; end
18
16
 
@@ -40,35 +38,37 @@ module Rubik
40
38
  disposed: []
41
39
  }.transform_values(&:freeze).freeze
42
40
 
43
- # Attention vocabulary (the tool plane's "needs attention" classification,
44
- # derived here so a state rename can never silently desync it — the tool
45
- # layer hand-copied these until now). PARKED_STATES is the vocabulary's
46
- # own words for the condvar-parked set; ATTENTION_STATES rides
47
- # :waiting_input on top. A named owned constant, not a computation from
48
- # TRANSITIONS — no clean derivation from the edges exists.
41
+ # Attention vocabulary (the tool plane's "needs attention" set,
42
+ # derived here so a rename can never silently desync it).
43
+ # PARKED_STATES is the condvar-parked set; ATTENTION_STATES rides
44
+ # :waiting_input on top. Owned constants — no clean derivation
45
+ # from the TRANSITIONS edges exists.
49
46
  PARKED_STATES = [:paused_error, :waiting_budget, :budget_exhausted].freeze
50
47
  ATTENTION_STATES = (PARKED_STATES + [:waiting_input]).freeze
51
48
 
52
- # --- Predicates: control-flow questions answer here, not at
53
- # consumers. All take the re-entrant monitor; callers composing
54
- # them under a held lock pay nothing extra, and external readers
55
- # see consistent snapshots.
49
+ # --- Predicates: control-flow questions answer here. All take the
50
+ # re-entrant monitor (re-entrant: composition under a held lock
51
+ # pays nothing extra; readers see consistent snapshots).
56
52
 
57
- # Worker thread mid-flight (possibly parked on a steering, budget,
58
- # or error wait).
53
+ # Worker thread mid-flight (possibly parked on a wait).
59
54
  def running?
60
55
  @monitor.synchronize { @state == :running || @state == :waiting_input || @state == :waiting_budget || @state == :paused_error }
61
56
  end
62
57
 
63
- # Occupies a concurrency slot / tracked in Supervisor#instances.
64
- # Composed from the vocabulary's own words: everything live except
65
- # :budget_exhausted (deliberately excluded, pinned by
66
- # test_pause_and_await_budget_expansion_timeout; supervisor's
67
- # send_message compensates via deliverable?).
58
+ # Occupies a concurrency slot / tracked in Supervisor#instances:
59
+ # everything live except :budget_exhausted (deliberately excluded,
60
+ # pinned by test_pause_and_await_budget_expansion_timeout;
61
+ # supervisor's send_message compensates via deliverable?).
68
62
  def active?
69
63
  @monitor.synchronize { pending? || running? || canceling? }
70
64
  end
71
65
 
66
+ # Issue #594, dispatched-work view: active? PLUS :budget_exhausted —
67
+ # a parked unit holds no slot (see active?) but its work is unfinished.
68
+ def in_flight?
69
+ @monitor.synchronize { pending? || running? || canceling? || @state == :budget_exhausted }
70
+ end
71
+
72
72
  def pending? = @monitor.synchronize { @state == :pending }
73
73
  def executing? = @monitor.synchronize { @state == :running }
74
74
  def awaiting_human? = @monitor.synchronize { @state == :waiting_input }
@@ -34,7 +34,11 @@ module Rubik
34
34
  return false unless inst
35
35
 
36
36
  if inst.deliverable?
37
- inst.post_message(message, sender: eff_sender, additional_steps: additional_steps)
37
+ # in_reply_to (#595-4 follow-up): an ask_question answer pairs
38
+ # against the instance's pending question id; nil for steering.
39
+ inst.post_message(message, sender: eff_sender,
40
+ additional_steps: additional_steps,
41
+ in_reply_to: kwargs[:in_reply_to])
38
42
  return true
39
43
  end
40
44
 
@@ -55,7 +55,8 @@ module Rubik
55
55
  def guidance(state, id:, max_steps:, step: nil, uptime: nil)
56
56
  case state.to_sym
57
57
  when :waiting_input
58
- "Subagent asked a question and is BLOCKED awaiting your answer. Reply via send_message(recipient: '#{id}', message: '<your answer>')."
58
+ "Subagent asked a question and is BLOCKED awaiting your answer. Reply via send_message(recipient: '#{id}', " \
59
+ "message: '<your answer>', in_reply_to: '<question_id from the question notification>')."
59
60
  when :waiting_budget
60
61
  Notices.budget_paused_line(id, max_steps)
61
62
  when :budget_exhausted
@@ -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
@@ -89,6 +89,8 @@ module Rubik
89
89
  notice[:reason] = raw_err.to_s.slice(0, kind == :question ? 300 : 120)
90
90
  end
91
91
  notice[:timeout] = payload[:timeout] if kind == :question
92
+ # Answer pairing (#595-4 follow-up): the reply echoes this id via send_message(in_reply_to: ...).
93
+ notice[:question_id] = payload[:question_id].to_s if kind == :question && payload[:question_id]
92
94
  # Kanonik referanslar (#122/#129): sonuç + transcript okuma adresleri bildirimle taşınır.
93
95
  notice[:result_ref] = payload[:result_ref].to_s if payload[:result_ref]
94
96
  notice[:transcript_ref] = payload[:transcript_ref].to_s if payload[:transcript_ref]
@@ -142,6 +144,7 @@ module Rubik
142
144
  reason_kinds = [:context_compacted, :auto_apply_failed, :error_paused, :message, :task, :question]
143
145
  attrs[:reason] = notice[:reason] if reason_kinds.include?(notice[:kind]) && !notice[:reason].to_s.empty?
144
146
  attrs[:timeout] = notice[:timeout] if notice[:kind] == :question && notice[:timeout]
147
+ attrs[:question_id] = notice[:question_id] if notice[:kind] == :question && notice[:question_id]
145
148
  attrs[:guidance] = guidance_for(notice)
146
149
  rendered = attrs.map { |k, v| %(#{k}="#{Rubik::Platform.xml_escape(v)}") }.join(" ")
147
150
  "<notification #{rendered} />"
@@ -170,8 +173,9 @@ module Rubik
170
173
  when :question
171
174
  answered = "No answer is needed anymore: it timed out and the subagent proceeded on its own judgment. " \
172
175
  "A late send_message(recipient: '#{notice[:id]}') lands as a regular message."
173
- blocking = "Answer NOW via send_message(recipient: '#{notice[:id]}', message: '<your answer>') — " \
174
- "the subagent is blocked waiting (#{notice[:timeout] || 300}s timeout)."
176
+ blocking = "Answer NOW via send_message(recipient: '#{notice[:id]}', message: '<your answer>', " \
177
+ "in_reply_to: '#{notice[:question_id]}') — the subagent is blocked waiting " \
178
+ "(#{notice[:timeout] || 300}s timeout); unpaired messages land as regular steering."
175
179
  notice[:state] == "question_timed_out" ? answered : blocking
176
180
  else
177
181
  if notice[:state] == "budget_exhausted"
@@ -1,5 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "securerandom"
4
+
3
5
  require_relative "../../storage/layout"
4
6
 
5
7
  module Rubik
@@ -29,13 +31,18 @@ module Rubik
29
31
  # step top): a pre-question inbox message was NOT sent to a
30
32
  # question-waiting subagent and must not pose as its answer.
31
33
  drain_inbox_into_history
34
+ question_id = "q-#{SecureRandom.hex(4)}"
32
35
  reason = Array(options).empty? ? question_text.to_s : "#{question_text} (options: #{Array(options).join(' / ')})"
33
- payload = { id: @id, role: @role, state: :waiting_input,
36
+ payload = { id: @id, role: @role, state: :waiting_input, question_id: question_id,
34
37
  reason: reason, timeout: question_timeout(timeout) }
35
38
  @monitor.synchronize do
36
39
  return :unavailable unless executing?
37
40
 
38
41
  transition!(:waiting_input)
42
+ # Open the pairing slot (issue #595-4 follow-up): only a reply
43
+ # that echoes THIS id poses as the answer, so a steering message
44
+ # pushed mid-window can never be consumed as the answer.
45
+ @pending_question_id = question_id
39
46
  @unit&.sync_state!
40
47
  end
41
48
  answer = nil
@@ -46,9 +53,28 @@ module Rubik
46
53
  Notices.emit(@event_bus, Notices::QUESTION_EVENT, payload)
47
54
  deadline = Time.now + payload[:timeout]
48
55
  @monitor.synchronize { @answer_cond ||= @monitor.new_cond }
56
+ unclaimed = []
49
57
  until answer
50
58
  @monitor.synchronize do
51
- answer = @inbox.pop(true)&.text unless @inbox.empty?
59
+ # Only messages whose in_reply_to matches the pending
60
+ # question id pose as the answer (issue #595-4 follow-up):
61
+ # the push-time answer tag now requires the pairing, so a
62
+ # steering message arriving DURING the :waiting_input window
63
+ # — pushed without a matching in_reply_to — is stashed and
64
+ # re-queued below so the next step-top drain delivers it as
65
+ # a normal message row instead.
66
+ until answer || @inbox.empty?
67
+ begin
68
+ msg = @inbox.pop(true)
69
+ rescue ThreadError
70
+ break
71
+ end
72
+ if msg&.answer && msg.in_reply_to == question_id
73
+ answer = msg.text
74
+ else
75
+ unclaimed << msg
76
+ end
77
+ end
52
78
  # Sleep on the cond var INSIDE the monitor (wait atomically
53
79
  # releases it), bounded by the deadline. The emitter's
54
80
  # broadcast outside the critical section cannot be lost:
@@ -58,9 +84,21 @@ module Rubik
58
84
  break if Time.now >= deadline || !(awaiting_human? || executing?)
59
85
  end
60
86
  ensure
61
- # Guarded restore (also covers a raise or Thread#kill mid-wait):
62
- # grant_budget! or kill may have legitimately moved the state on.
87
+ # Re-queue unclaimed messages in arrival order so
88
+ # drain_inbox_into_history (next step top) delivers them — the
89
+ # worker is still the only drainer here (it is this thread,
90
+ # blocked inside the tool). A failed re-queue must be observable,
91
+ # never silently swallowed (AGENTS.md §5).
92
+ begin
93
+ unclaimed&.each { |msg| @inbox.push(msg) }
94
+ rescue StandardError => e
95
+ Rubik::Log.warn(:subagent, "[Questioner] re-queue of #{unclaimed.to_a.size} unclaimed " \
96
+ "inbox message(s) failed: #{e.class}: #{e.message}")
97
+ end
98
+ # Close the pairing slot BEFORE the guarded restore: after this
99
+ # point no push can claim the (now dead) question id.
63
100
  @monitor.synchronize do
101
+ @pending_question_id = nil
64
102
  transition!(:running) if awaiting_human?
65
103
  @unit&.sync_state!
66
104
  end