rubik 0.14.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 (65) hide show
  1. checksums.yaml +4 -4
  2. data/ATTRIBUTION.md +1 -1
  3. data/CHANGELOG.md +89 -1
  4. data/lib/rubik/adapter/node.rb +4 -1
  5. data/lib/rubik/ast/fallback_cleaner.rb +6 -1
  6. data/lib/rubik/ast/ruby_extractor.rb +12 -6
  7. data/lib/rubik/buffer/manager.rb +15 -10
  8. data/lib/rubik/buffer/snapshot.rb +103 -35
  9. data/lib/rubik/config/scoped.rb +12 -5
  10. data/lib/rubik/connect/models_dev.rb +4 -2
  11. data/lib/rubik/connect/wizard.rb +9 -1
  12. data/lib/rubik/diagnostics/collector.rb +25 -2
  13. data/lib/rubik/llm/client.rb +19 -0
  14. data/lib/rubik/llm/connection_pool.rb +7 -1
  15. data/lib/rubik/llm/formatter.rb +8 -2
  16. data/lib/rubik/llm/router.rb +8 -0
  17. data/lib/rubik/lsp/client.rb +233 -18
  18. data/lib/rubik/lsp/document_store.rb +6 -0
  19. data/lib/rubik/lsp/manager.rb +14 -0
  20. data/lib/rubik/lsp/transport.rb +17 -0
  21. data/lib/rubik/orchestrator/continuation_manager.rb +54 -2
  22. data/lib/rubik/orchestrator/goal_session.rb +10 -10
  23. data/lib/rubik/orchestrator/goal_wait.rb +15 -9
  24. data/lib/rubik/orchestrator/loop.rb +31 -28
  25. data/lib/rubik/orchestrator/subagent/instance.rb +22 -4
  26. data/lib/rubik/orchestrator/subagent/lifecycle.rb +25 -25
  27. data/lib/rubik/orchestrator/subagent/messaging.rb +5 -1
  28. data/lib/rubik/orchestrator/subagent/narration.rb +2 -1
  29. data/lib/rubik/orchestrator/subagent/notices.rb +6 -2
  30. data/lib/rubik/orchestrator/subagent/questioner.rb +42 -4
  31. data/lib/rubik/orchestrator/subagent/reaper.rb +50 -19
  32. data/lib/rubik/orchestrator/subagent/supervisor.rb +11 -0
  33. data/lib/rubik/orchestrator/tool_call_id.rb +8 -4
  34. data/lib/rubik/orchestrator/turn_executor/subagent_channel.rb +21 -5
  35. data/lib/rubik/orchestrator/turn_executor/user_channel.rb +15 -2
  36. data/lib/rubik/platform/process.rb +32 -7
  37. data/lib/rubik/platform/sanitize.rb +17 -18
  38. data/lib/rubik/platform.rb +27 -0
  39. data/lib/rubik/plugin/storage.rb +17 -11
  40. data/lib/rubik/prompt/doctrine.rb +3 -2
  41. data/lib/rubik/repl/commands/base.rb +7 -3
  42. data/lib/rubik/repl/commands/buffer.rb +6 -2
  43. data/lib/rubik/repl/commands/session.rb +11 -1
  44. data/lib/rubik/repl/input_execution.rb +3 -3
  45. data/lib/rubik/repl/service_catalog.rb +6 -2
  46. data/lib/rubik/repl/turn_recorder.rb +4 -1
  47. data/lib/rubik/runtime/manifest_store.rb +7 -2
  48. data/lib/rubik/runtime/task_manager.rb +13 -10
  49. data/lib/rubik/sandbox/driver/base.rb +34 -0
  50. data/lib/rubik/sandbox/driver/bubblewrap.rb +2 -0
  51. data/lib/rubik/sandbox/driver/docker.rb +8 -0
  52. data/lib/rubik/sandbox/driver/podman.rb +8 -0
  53. data/lib/rubik/sandbox/driver/process.rb +9 -12
  54. data/lib/rubik/security/path_policy.rb +28 -3
  55. data/lib/rubik/session/recorder.rb +14 -2
  56. data/lib/rubik/storage/store.rb +7 -0
  57. data/lib/rubik/tools/builtins/exec.rb +7 -1
  58. data/lib/rubik/tools/builtins/interactive.rb +5 -2
  59. data/lib/rubik/tools/builtins/lsp.rb +28 -2
  60. data/lib/rubik/tools/builtins/send_message.rb +7 -2
  61. data/lib/rubik/tools/preflight_runner.rb +4 -1
  62. data/lib/rubik/ui/dialog.rb +5 -1
  63. data/lib/rubik/ui/renderer.rb +4 -1
  64. data/lib/rubik/version.rb +1 -1
  65. metadata +1 -1
@@ -26,13 +26,11 @@ module Rubik
26
26
  class Loop
27
27
  attr_accessor :history, :invalid_tool_count, :last_turn_streamed, :context_warning_emitted, :loop_context
28
28
  attr_reader :max_steps, :step_count, :model, :total_tokens, :warn_at_ratio, :runtime_manager, :context_limit, :max_output_tokens, :config
29
- # Collaborator-facing state (Plan 54 D-5): loop state physically stays on Loop;
30
- # 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.
31
30
  attr_reader :provider, :on_step, :tool_registry, :shell, :buffer_manager, :lsp_manager, :step_executor,
32
31
  :budget_manager, :stream_manager, :activity
33
32
 
34
- # Channel-owned counter (TurnExecutor::NudgePolicy); the public reader
35
- # name is load-bearing (tests, REPL surfaces).
33
+ # Channel-owned counter (TurnExecutor::NudgePolicy); public reader name is load-bearing.
36
34
  def empty_response_count = turn_executor.nudge_policy.count
37
35
 
38
36
  def initialize(provider:, tool_registry:, max_steps: 40, warn_at_ratio: 0.75, model: nil, on_step: nil, shell: nil, context_limit: nil,
@@ -177,27 +175,32 @@ module Rubik
177
175
  end
178
176
  end
179
177
 
180
- # auto: unattended auto-extension (!goal auto-continue) — the model
181
- # 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".
182
179
  def continue_loop(extra_steps = 20, plan_only: false, auto: false)
183
- # Retention seam — see SubagentNoticeInbox#keep_for_continuation.
184
- subagent_notice_inbox.keep_for_continuation
185
- extend_budget(extra_steps)
186
- target_model = @model
187
- opts = target_model ? { model: target_model } : {}
188
- opts[:tools] = @tool_registry.schemas
189
-
190
- # Plan 61 D-14: notifications travel as their own user message —
191
- # appending to @history.last may target a tool result or a
192
- # content-less assistant message, which provider formatters then
193
- # 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)
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
201
204
  end
202
205
 
203
206
  # ── !goal resume (issue #106) ─────────────────────────────────────
@@ -317,8 +320,8 @@ module Rubik
317
320
  )
318
321
  end
319
322
 
320
- # Lightweight fingerprint of environment factors that affect the rendered system prompt.
321
- # 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.
322
325
  def prompt_state_fingerprint(plan_only: false)
323
326
  tools = plan_only ? [] : (@tool_registry&.schemas&.map { |s| s[:name] || s["name"] } || [])
324
327
  skills = Rubik::Coeffects.get(@runtime_manager&.context, Rubik::Coeffects::SKILL_MANAGER)&.prompt_index
@@ -329,8 +332,8 @@ module Rubik
329
332
  [tools, skills, subagents, dirty, lsp_diags].hash
330
333
  end
331
334
 
332
- # Dynamically updates @history[0] in-place if tools, skills, subagents, dirty files or LSP
333
- # 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.
334
337
  def refresh_system_prompt_if_needed!(mode:, plan_only:, extra_context: nil)
335
338
  return unless @history&.first && Prompt::ConversationRows.role_of(@history.first) == "system"
336
339
  return if (current_fp = prompt_state_fingerprint(plan_only: plan_only)) == @last_prompt_fingerprint
@@ -115,6 +115,7 @@ module Rubik
115
115
  @thread = nil
116
116
  @start_gate = nil
117
117
  @start_aborted = false
118
+ @pending_question_id = nil
118
119
  end
119
120
 
120
121
  def uptime = @started_at ? ((@ended_at || Time.now) - @started_at).to_f : 0.0
@@ -149,12 +150,29 @@ module Rubik
149
150
  # Inbox girdisi: mesaj metni + GERÇEK gönderen id'si. nil veya makine
150
151
  # adı "agent-0" gönderenler render'da maestro persona'sına çevrilir
151
152
  # (iki-düzlem adlandırma sözleşmesi) — subagent gönderenler kendi
152
- # id'leriyle görünür (drain: StepRunner#sender_label).
153
- 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
154
168
 
155
- def post_message(message, sender: nil, additional_steps: nil)
169
+ def post_message(message, sender: nil, additional_steps: nil, in_reply_to: nil)
156
170
  @monitor.synchronize do
157
- @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))
158
176
  if error_paused?
159
177
  resume!(additional_steps: additional_steps)
160
178
  elsif awaiting_budget? || additional_steps
@@ -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
@@ -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
@@ -27,9 +27,13 @@ module Rubik
27
27
  # dosya yoksa reap sonraki süpürmeye kalır (yarım tasfiye yok). After
28
28
  # TRANSCRIPT_ARCHIVE_MAX_RETRIES the durability gate is released with
29
29
  # a warning so a permanently-failing save cannot strand the instance.
30
- def archive!
30
+ # `durable:` lets the supervisor sweep pre-probe the transcript OUTSIDE
31
+ # its monitor (issue #595-5) and hand the verdict in; nil probes here
32
+ # (legacy direct callers keep the retry semantics untouched).
33
+ def archive!(durable: nil)
31
34
  @monitor.synchronize do
32
- unless File.exist?(@transcript_uri.to_s)
35
+ exists = durable.nil? ? File.exist?(@transcript_uri.to_s) : durable
36
+ unless exists
33
37
  @archive_retries = (@archive_retries || 0) + 1
34
38
  if @archive_retries < TRANSCRIPT_ARCHIVE_MAX_RETRIES
35
39
  return false # transient: leave it for the next sweep
@@ -52,30 +56,54 @@ module Rubik
52
56
  # bilinçli olarak yalnız @instances'e bakar (reap edilen zaten
53
57
  # notice ile duyurulmuş, sonucu transcriptte).
54
58
  module ReaperSupervisor
59
+ # Three-pass sweep (issue #595-5): the supervisor monitor is held
60
+ # only for STATE BOOKKEEPING. Pass 1 snapshots the candidates and
61
+ # releases the lock; the transcript durability probes (File.exist?)
62
+ # and the tombstone cleanups run OUTSIDE it, so spawn/send_message/
63
+ # status are never stalled behind FS IO. Pass 2 keeps archive! UNDER
64
+ # the monitor on purpose: the redeploy plane shares this monitor
65
+ # exactly so an archive cannot interleave a redeployable? check
66
+ # (reuse.rb buffer_for_redeploy) — that invariant is not negotiable.
55
67
  def reap_finished!(force: false)
56
- dropped_steering = []
57
- reaped = @monitor.synchronize do
58
- grace = reap_grace_seconds
59
- reaped = []
60
- @instances.each do |id, inst|
68
+ grace = reap_grace_seconds
69
+ candidates = @monitor.synchronize do
70
+ @instances.values.select do |inst|
61
71
  next unless inst.respond_to?(:terminal_and_settled?) && inst.terminal_and_settled?
62
- next unless force || (grace && inst.ended_at && Time.now - inst.ended_at >= grace)
63
- next unless inst.archive!
64
72
 
65
- dropped_steering << id if inst.respond_to?(:pending_redeploy_messages?) && inst.pending_redeploy_messages?
66
- @finished[id] = inst
67
- reaped << id
73
+ force || (grace && inst.ended_at && Time.now - inst.ended_at >= grace)
74
+ end
75
+ end
76
+ # OUTSIDE the supervisor monitor: per-candidate transcript probe.
77
+ durability = candidates.to_h { |inst| [inst.id, File.exist?(inst.transcript_uri.to_s)] }
78
+
79
+ dropped_steering = []
80
+ reaped_ids = evicted = nil
81
+ @monitor.synchronize do
82
+ reaped_ids = []
83
+ evicted = []
84
+ candidates.each do |inst|
85
+ # Re-checks (redeploy may have revived it between the passes);
86
+ # archive! + tombstone move stay atomic against the redeploy
87
+ # plane by sharing this monitor.
88
+ next unless @instances[inst.id].equal?(inst) && inst.terminal_and_settled?
89
+ next unless inst.archive!(durable: durability[inst.id])
90
+
91
+ dropped_steering << inst.id if inst.respond_to?(:pending_redeploy_messages?) && inst.pending_redeploy_messages?
92
+ @finished[inst.id] = inst
93
+ reaped_ids << inst.id
68
94
  end
69
- reaped.each { |id| @instances.delete(id) }
70
- evict_overflow!
71
- reaped
95
+ reaped_ids.each { |id| @instances.delete(id) }
96
+ evicted = evict_overflow!
72
97
  end
98
+ # OUTSIDE the supervisor monitor: tombstone overflow cleanup
99
+ # (context dispose) must not stall live-plane operations.
100
+ evicted.each(&:cleanup)
73
101
  # OUTSIDE the supervisor monitor (emit/logging discipline): queued
74
102
  # steering that died with the instance instead of a redeploy — the
75
103
  # send_message :queued reply discloses this, but the loss must be
76
104
  # observable (issue #55 3.2).
77
105
  Platform.debug_warn("[Reaper] reaped with undelivered queued steering: #{dropped_steering.join(', ')}") unless dropped_steering.empty?
78
- reaped
106
+ reaped_ids
79
107
  end
80
108
 
81
109
  private
@@ -99,13 +127,16 @@ module Rubik
99
127
  Rubik::Storage::Layout.config_get(@config, "subagents.tombstone_limit", 25).to_i
100
128
  end
101
129
 
102
- # FIFO taşma: en eski mezar taşı evict edilir ve cleanup ile
103
- # :disposed'a çekilir (ctx zaten dispose'lu; cleanup no-op güvenli).
130
+ # FIFO taşma: en eski mezar taşları evict edilir ve CALLING SIDE'a
131
+ # döner — cleanup (:disposed'a çekme, context dispose) monitor
132
+ # DIŞINDA çalışır (issue #595-5).
104
133
  def evict_overflow!
134
+ evicted = []
105
135
  while @finished.size > tombstone_limit
106
136
  _id, inst = @finished.shift
107
- inst&.cleanup
137
+ evicted << inst if inst
108
138
  end
139
+ evicted
109
140
  end
110
141
  end
111
142
  end
@@ -191,6 +191,17 @@ module Rubik
191
191
  end
192
192
  end
193
193
 
194
+ # Dispatched-work view for the goal-completion guard (issue #594):
195
+ # in_flight? units — active? (slot-holding) PLUS :budget_exhausted
196
+ # parked mid-task. Concurrency-slot accounting keeps active_count;
197
+ # the completion guard must not declare a goal achieved while a
198
+ # parked unit still owes a result.
199
+ def dispatched_count
200
+ @monitor.synchronize do
201
+ @instances.values.count(&:in_flight?)
202
+ end
203
+ end
204
+
194
205
  def active_count
195
206
  @monitor.synchronize do
196
207
  @instances.values.count(&:active?)
@@ -13,10 +13,14 @@ module Rubik
13
13
  # and a deterministic "call_3_1" WILL recur inside one history —
14
14
  # duplicate tool_use ids break strict providers' tool_result
15
15
  # pairing. The 4-digit random suffix is load-bearing, not decor.
16
- # - Subagent StepRunner (deterministic): a subagent's history lives
17
- # and dies with its own run — never restored, never continued — so
18
- # (subagent id, step, index) is unique by construction, and
19
- # determinism keeps ids greppable across subagents in transcripts.
16
+ # - Subagent StepRunner (deterministic): (subagent id, run, step,
17
+ # index) is unique by construction and determinism keeps ids
18
+ # greppable across subagents in transcripts. The run component is
19
+ # load-bearing (issue #593): Redeploy preserves @history and mints
20
+ # a fresh Budget, so step restarts at 0 while the OLD ids stay in
21
+ # the re-sent history — run_seq (incremented by every start_async,
22
+ # spawn and redeploy alike) is what keeps the redeployed run's ids
23
+ # disjoint from the preserved ones.
20
24
  # - StepExecutor (unique: true): dead on the production path (the
21
25
  # TurnExecutor normalizes ids before dispatch) but live on the
22
26
  # executor's own seam — test doubles call it with bare, id-less tool
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "../tool_call_id"
4
+ require_relative "../tool_history"
4
5
 
5
6
  module Rubik
6
7
  module Orchestrator
@@ -32,10 +33,13 @@ module Rubik
32
33
  end
33
34
 
34
35
  # Subagent policy (ToolCallId doctrine): deterministic
35
- # (subagent id, step, index) — the history lives and dies with the
36
- # run, and greppable ids beat collision-proof ones here.
36
+ # (subagent id, run, step, index). run_seq increments on every
37
+ # start_async — spawn AND redeploy alike — so a redeployed run's
38
+ # ids can never collide with the preserved history it re-sends to
39
+ # the provider (issue #593). Greppable ids still beat
40
+ # collision-proof ones here.
37
41
  def mint_call_id(idx)
38
- ToolCallId.mint(@inst.id, @inst.current_step, idx + 1)
42
+ ToolCallId.mint(@inst.id, @inst.run_seq, @inst.current_step, idx + 1)
39
43
  end
40
44
 
41
45
  # ── response shaping ──
@@ -90,15 +94,27 @@ module Rubik
90
94
  @inst.history << { role: "assistant", content: final_text.empty? ? nil : final_text, tool_calls: tool_calls }
91
95
  end
92
96
 
93
- def on_finish(args, fallback_text)
97
+ # The assistant row carrying the finish tool_use was already
98
+ # recorded; it needs a pairing tool-result row before
99
+ # complete_turn! or the preserved history hands strict providers
100
+ # an orphaned tool_use on the next request (issue #593 — mirrors
101
+ # StepExecutor#handle_finish_tool and the user channel's deferred
102
+ # finish path).
103
+ def on_finish(args, fallback_text, call_id = nil)
94
104
  message = args["message"] || args[:message] || fallback_text || "Completed"
95
105
  @inst.auto_apply_buffer!(:finish) unless @inst.workspace == "branch"
106
+ if call_id
107
+ Rubik::Orchestrator::ToolHistory.write(
108
+ @inst.history, tool_call_id: call_id, tool_name: "finish",
109
+ status: :ok, duration_ms: 0.0, content: message.to_s
110
+ )
111
+ end
96
112
  @inst.complete_turn!(message)
97
113
  { ok: true, completed: true }
98
114
  end
99
115
 
100
116
  def execute_tool_call(tool_call, text)
101
- return on_finish(tool_call["args"] || {}, text) if TurnExecutor.finish_call?(@inst.tool_registry, tool_call)
117
+ return on_finish(tool_call["args"] || {}, text, tool_call["id"]) if TurnExecutor.finish_call?(@inst.tool_registry, tool_call)
102
118
 
103
119
  @inst.execute_subagent_tool_call(tool_call)
104
120
  nil
@@ -69,9 +69,11 @@ module Rubik
69
69
 
70
70
  # Stitch the RAW response (sanitized): `text` was already stripped
71
71
  # by TurnExecutor#call, which would eat the leading indentation of
72
- # the continuation chunk (issue #547).
72
+ # the continuation chunk (issue #547). The history is handed in so
73
+ # the prior partial assistant rows are absorbed — the stitched
74
+ # full text must not duplicate them (issue #595-1).
73
75
  raw_text = res.respond_to?(:text) ? res.text : text
74
- cm.stitch_and_reset(Platform.safe_utf8(raw_text).to_s)
76
+ cm.stitch_and_reset(Platform.safe_utf8(raw_text).to_s, history: @deps.history)
75
77
  end
76
78
 
77
79
  def track_usage(res) = @deps.budget_manager.track_token_usage!(res)
@@ -113,6 +115,17 @@ module Rubik
113
115
  end
114
116
  return nil unless trunc_action[:error]
115
117
 
118
+ # Failure terminal (auto-continue disabled or ceiling exhausted):
119
+ # the generated content must not be dropped from history (issue
120
+ # #595-2). Persist buffer + current partial as ONE assistant row,
121
+ # absorbing any prior partial rows so nothing is duplicated —
122
+ # the same invariant as the stitch path.
123
+ accumulated = cm.continuation_buffer + safe_text
124
+ unless accumulated.strip.empty?
125
+ cm.absorb_partial_rows!(@deps.history)
126
+ @deps.history << { role: "assistant", content: accumulated }
127
+ end
128
+
116
129
  @deps.on_step&.call(type: :error, content: trunc_action[:error], step: @deps.step_count, max_steps: @deps.max_steps)
117
130
  @deps.loop_instance.turn_result(success: false, error: trunc_action[:error])
118
131
  end