rubik 0.15.1 → 0.15.3

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 (55) hide show
  1. checksums.yaml +4 -4
  2. data/ATTRIBUTION.md +1 -1
  3. data/CHANGELOG.md +67 -2
  4. data/lib/rubik/ast/cache_store.rb +22 -4
  5. data/lib/rubik/ast/extractor.rb +1 -4
  6. data/lib/rubik/ast/ruby_extractor.rb +23 -1
  7. data/lib/rubik/ast/symbol.rb +9 -4
  8. data/lib/rubik/ast/treesitter/python_walker.rb +5 -4
  9. data/lib/rubik/ast/treesitter_extractor.rb +10 -3
  10. data/lib/rubik/buffer/diff.rb +34 -2
  11. data/lib/rubik/buffer/manager.rb +18 -15
  12. data/lib/rubik/buffer/path_validator.rb +18 -2
  13. data/lib/rubik/buffer/snapshot.rb +144 -9
  14. data/lib/rubik/concurrency/timers.rb +7 -0
  15. data/lib/rubik/config/scoped.rb +18 -7
  16. data/lib/rubik/config/secret_policy.rb +22 -1
  17. data/lib/rubik/config.rb +24 -26
  18. data/lib/rubik/context/ignore_rules.rb +7 -2
  19. data/lib/rubik/diagnostics/parser.rb +19 -8
  20. data/lib/rubik/kernel/dispatcher.rb +11 -5
  21. data/lib/rubik/llm/client.rb +24 -3
  22. data/lib/rubik/llm/connection_pool.rb +51 -30
  23. data/lib/rubik/llm/message_sanitizer.rb +20 -1
  24. data/lib/rubik/llm/sse_parser.rb +10 -1
  25. data/lib/rubik/lsp/client.rb +9 -2
  26. data/lib/rubik/lsp/manager.rb +43 -40
  27. data/lib/rubik/lsp/transport.rb +61 -1
  28. data/lib/rubik/mcp/transport/stdio.rb +143 -131
  29. data/lib/rubik/orchestrator/activity_log.rb +3 -2
  30. data/lib/rubik/orchestrator/goal_session.rb +14 -14
  31. data/lib/rubik/orchestrator/loop.rb +11 -12
  32. data/lib/rubik/orchestrator/subagent/completion.rb +18 -8
  33. data/lib/rubik/orchestrator/turn_executor/user_channel.rb +5 -1
  34. data/lib/rubik/platform/process.rb +74 -19
  35. data/lib/rubik/platform.rb +16 -16
  36. data/lib/rubik/plugin/manager.rb +5 -6
  37. data/lib/rubik/repl/service_catalog.rb +1 -1
  38. data/lib/rubik/repl/terminal_guard.rb +29 -23
  39. data/lib/rubik/repl/turn_recorder.rb +35 -11
  40. data/lib/rubik/sandbox/driver/base.rb +26 -3
  41. data/lib/rubik/sandbox/driver/bubblewrap.rb +6 -11
  42. data/lib/rubik/sandbox/driver/docker.rb +1 -11
  43. data/lib/rubik/sandbox/driver/podman.rb +26 -18
  44. data/lib/rubik/sandbox/driver/process.rb +16 -35
  45. data/lib/rubik/security/blocked_guidance.rb +4 -2
  46. data/lib/rubik/security/command_gate.rb +27 -14
  47. data/lib/rubik/security/errors.rb +13 -0
  48. data/lib/rubik/security/guard.rb +11 -2
  49. data/lib/rubik/security/path_policy.rb +9 -6
  50. data/lib/rubik/storage/store.rb +31 -11
  51. data/lib/rubik/tools/builtins/exec.rb +5 -1
  52. data/lib/rubik/tools/builtins/files.rb +2 -0
  53. data/lib/rubik/tools/uri_resolver.rb +23 -3
  54. data/lib/rubik/version.rb +1 -1
  55. metadata +1 -1
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "open3"
4
+ require "monitor"
4
5
  require "json"
5
6
  require "shellwords"
6
7
  require_relative "../errors"
@@ -22,13 +23,6 @@ module Rubik
22
23
  # Errno::EPIPE after this many seconds instead of a deadlock.
23
24
  STDIN_WRITE_TIMEOUT = 5.0
24
25
 
25
- # Credential-shaped variable names stripped from the inherited host
26
- # environment when a server opts out with `inherit_env: false`. Only
27
- # the suffix shape is policy — the prefix is the provider's choice
28
- # (GITHUB_TOKEN, ANTHROPIC_API_KEY, AWS_SECRET_ACCESS_KEY, GITHUB_PAT,
29
- # DATABASE_URL, ...), so we match it broadly.
30
- CREDENTIAL_ENV_PATTERN = /_(KEY|TOKEN|SECRET|PASSWORD|PAT)\z|\A(DATABASE|REDIS|MONGO|POSTGRES|MYSQL|AMQP)_URL\z|_(DATABASE|REDIS|CONNECTION)_URL\z/i
31
-
32
26
  attr_reader :command, :args, :env, :inherit_env, :root_dir, :running, :wait_thr
33
27
 
34
28
  def initialize(command, args: [], env: {}, inherit_env: true, root_dir: Dir.pwd, guard: nil)
@@ -49,6 +43,9 @@ module Rubik
49
43
  @stderr_mutex = Mutex.new
50
44
  @stderr_tail = []
51
45
  @mutex = Mutex.new
46
+ # Serializes the whole check-spawn-assign lifecycle; close takes the
47
+ # same monitor so a concurrent teardown cannot race an open.
48
+ @lifecycle_monitor = Monitor.new
52
49
  # Writes are serialized on their OWN mutex, never @mutex: @mutex is
53
50
  # also taken by close/wait_for_response/the reader, so a stalled
54
51
  # write holding it would wedge teardown and response delivery.
@@ -57,72 +54,83 @@ module Rubik
57
54
  @responses = {}
58
55
  @closed = false
59
56
  @generation = 0
57
+ @child_identity = nil
60
58
  @pending_requests = Set.new
61
59
  end
62
60
 
63
61
  def open
64
- return if running?
65
-
66
- # A previous incarnation whose child died on its own (the reader's
67
- # ensure cleared @running) still holds pipe FDs and an unreaped
68
- # wait thread; re-spawning over them leaks both. close is
69
- # idempotent and a no-op when nothing lingers.
70
- close if @wait_thr || @reader_thr || @stderr_thr
71
-
72
- cmd_parts = if @args.empty? && @command.is_a?(String)
73
- begin
74
- Shellwords.split(@command)
75
- rescue ArgumentError => e
76
- raise ConnectionError, "Invalid command syntax: #{e.message}"
62
+ @lifecycle_monitor.synchronize do
63
+ return if running?
64
+
65
+ # A previous incarnation whose child died on its own (the reader's
66
+ # ensure cleared @running) still holds pipe FDs and an unreaped
67
+ # wait thread; re-spawning over them leaks both. close is
68
+ # idempotent and a no-op when nothing lingers.
69
+ close if @wait_thr || @reader_thr || @stderr_thr
70
+
71
+ cmd_parts = if @args.empty? && @command.is_a?(String)
72
+ begin
73
+ Shellwords.split(@command)
74
+ rescue ArgumentError => e
75
+ raise ConnectionError, "Invalid command syntax: #{e.message}"
76
+ end
77
+ else
78
+ [@command.to_s] + @args
77
79
  end
78
- else
79
- [@command.to_s] + @args
80
- end
81
-
82
- bin = cmd_parts.first
83
- raise ConnectionError, "MCP command cannot be empty" if bin.nil? || bin.empty?
84
-
85
- # Red-Team Defense: Verify command safety against destructive operations.
86
- # Route the MCP spawn command through the same Guard#verify_command_safety!
87
- # call that RunCommandTool uses — the narrow DANGEROUS_COMMAND_PATTERNS
88
- # subset below was a bypass: it misses many dangerous commands the
89
- # classifier flags. Fails closed on any dangerous/unmanaged command.
90
- full_cmd = Shellwords.shelljoin(cmd_parts)
91
- begin
92
- @guard.verify_command_safety!(full_cmd)
93
- rescue Rubik::Security::BlockedWriteError => e
94
- # No manual audit here: verify_command_safety! already logged
95
- # "blocked_command" with the TRUE classifier reason before raising
96
- # — a second hardcoded entry would double-log and mislabel it.
97
- raise ConnectionError, "Security blocked MCP process: #{e.message}"
98
- end
99
80
 
100
- resolved_bin = Rubik::Platform.which(bin)
101
- cmd_parts[0] = resolved_bin if resolved_bin
81
+ bin = cmd_parts.first
82
+ raise ConnectionError, "MCP command cannot be empty" if bin.nil? || bin.empty?
102
83
 
103
- # Match the LSP client's spawn hygiene: the host's bundler/Ruby
104
- # runtime variables are unset for the child, so an MCP server never
105
- # inherits a foreign BUNDLE_GEMFILE/RUBYOPT. Explicitly configured
106
- # env: entries merge on top and win.
107
- begin
108
- @stdin, @stdout, @stderr, @wait_thr = Open3.popen3(spawn_env, *cmd_parts, chdir: @root_dir)
109
- rescue SystemCallError => e
110
- raise ConnectionError, "Failed to spawn MCP process '#{bin}': #{e.message}"
111
- end
84
+ # Red-Team Defense: Verify command safety against destructive operations.
85
+ # Route the MCP spawn command through the same Guard#verify_command_safety!
86
+ # call that RunCommandTool uses — the narrow DANGEROUS_COMMAND_PATTERNS
87
+ # subset below was a bypass: it misses many dangerous commands the
88
+ # classifier flags. Fails closed on any dangerous/unmanaged command.
89
+ full_cmd = Shellwords.shelljoin(cmd_parts)
90
+ begin
91
+ @guard.verify_command_safety!(full_cmd)
92
+ rescue Rubik::Security::BlockedWriteError => e
93
+ # No manual audit here: verify_command_safety! already logged
94
+ # "blocked_command" with the TRUE classifier reason before raising
95
+ # — a second hardcoded entry would double-log and mislabel it.
96
+ raise ConnectionError, "Security blocked MCP process: #{e.message}"
97
+ end
112
98
 
113
- @mutex.synchronize do
114
- @running = true
115
- @closed = false
116
- @generation += 1
117
- @req_id = 0
118
- @responses.clear
119
- @pending_requests.clear
120
- end
121
- @stderr_mutex.synchronize { @stderr_tail.clear }
99
+ resolved_bin = Rubik::Platform.which(bin)
100
+ cmd_parts[0] = resolved_bin if resolved_bin
101
+
102
+ # Match the LSP client's spawn hygiene: the host's bundler/Ruby
103
+ # runtime variables are unset for the child, so an MCP server never
104
+ # inherits a foreign BUNDLE_GEMFILE/RUBYOPT. Explicitly configured
105
+ # env: entries merge on top and win.
106
+ begin
107
+ @stdin, @stdout, @stderr, @wait_thr = Open3.popen3(spawn_env, *cmd_parts, chdir: @root_dir)
108
+ rescue SystemCallError => e
109
+ raise ConnectionError, "Failed to spawn MCP process '#{bin}': #{e.message}"
110
+ end
111
+
112
+ # Snapshot the child's identity at spawn so teardown cannot signal a
113
+ # recycled PID (the guard in Platform.kill_tree needs it).
114
+ @child_identity = begin
115
+ Rubik::Platform.send(:process_identity, @wait_thr.pid)
116
+ rescue StandardError
117
+ nil
118
+ end
119
+
120
+ @mutex.synchronize do
121
+ @running = true
122
+ @closed = false
123
+ @generation += 1
124
+ @req_id = 0
125
+ @responses.clear
126
+ @pending_requests.clear
127
+ end
128
+ @stderr_mutex.synchronize { @stderr_tail.clear }
122
129
 
123
- start_stderr_thread
124
- start_reader_thread
125
- self
130
+ start_stderr_thread
131
+ start_reader_thread
132
+ self
133
+ end
126
134
  end
127
135
  alias start open
128
136
 
@@ -169,87 +177,89 @@ module Rubik
169
177
  end
170
178
 
171
179
  def close
172
- # Never take @write_mutex here: a writer may be stalled in
173
- # write_until, and killing the child (below) is precisely what
174
- # unblocks it. Waiting for the write lock would deadlock teardown.
175
- child_died = false
176
- # Capture before @wait_thr is nil'd below: the child-died diagnostic
177
- # must still report WHICH server process failed to start.
178
- exited_pid = @wait_thr&.pid
179
- @mutex.synchronize do
180
- return if @closed
181
-
182
- child_died = !@running
183
- @closed = true
184
- @running = false
185
- end
180
+ @lifecycle_monitor.synchronize do
181
+ # Never take @write_mutex here: a writer may be stalled in
182
+ # write_until, and killing the child (below) is precisely what
183
+ # unblocks it. Waiting for the write lock would deadlock teardown.
184
+ child_died = false
185
+ # Capture before @wait_thr is nil'd below: the child-died diagnostic
186
+ # must still report WHICH server process failed to start.
187
+ exited_pid = @wait_thr&.pid
188
+ @mutex.synchronize do
189
+ return if @closed
186
190
 
187
- begin
188
- @reader_thr&.kill
189
- rescue StandardError
190
- nil
191
- end
191
+ child_died = !@running
192
+ @closed = true
193
+ @running = false
194
+ end
192
195
 
193
- begin
194
- @stderr_thr&.kill
195
- rescue StandardError
196
- nil
197
- end
196
+ begin
197
+ @reader_thr&.kill
198
+ rescue StandardError
199
+ nil
200
+ end
198
201
 
199
- if @wait_thr&.alive?
200
- pid_to_kill = @wait_thr.pid
201
- Rubik::Platform.kill_tree(pid_to_kill)
202
202
  begin
203
- @wait_thr.join(0.5)
203
+ @stderr_thr&.kill
204
204
  rescue StandardError
205
205
  nil
206
206
  end
207
207
 
208
- if @wait_thr.alive?
209
- abandoned_waiter = @wait_thr
210
- Thread.new do
211
- begin
212
- abandoned_waiter.join(2.5)
213
- rescue StandardError
214
- nil
208
+ if @wait_thr&.alive?
209
+ pid_to_kill = @wait_thr.pid
210
+ Rubik::Platform.kill_tree(pid_to_kill, identity: @child_identity)
211
+ begin
212
+ @wait_thr.join(0.5)
213
+ rescue StandardError
214
+ nil
215
+ end
216
+
217
+ if @wait_thr.alive?
218
+ abandoned_waiter = @wait_thr
219
+ Thread.new do
220
+ begin
221
+ abandoned_waiter.join(2.5)
222
+ rescue StandardError
223
+ nil
224
+ end
225
+ Rubik::Log.warn(:mcp, "abandoned child process pid #{pid_to_kill} did not exit within reaper window") if abandoned_waiter.alive?
215
226
  end
216
- Rubik::Log.warn(:mcp, "abandoned child process pid #{pid_to_kill} did not exit within reaper window") if abandoned_waiter.alive?
217
227
  end
218
228
  end
219
- end
220
- @wait_thr = nil
229
+ @wait_thr = nil
221
230
 
222
- [@stdin, @stdout, @stderr].each do |io|
223
- io&.close unless io&.closed?
224
- rescue StandardError
225
- nil
226
- end
231
+ [@stdin, @stdout, @stderr].each do |io|
232
+ io&.close unless io&.closed?
233
+ rescue StandardError
234
+ nil
235
+ end
227
236
 
228
- begin
229
- @reader_thr&.join(0.5)
230
- rescue StandardError
231
- nil
232
- ensure
233
- @reader_thr = nil
234
- end
237
+ begin
238
+ @reader_thr&.join(0.5)
239
+ rescue StandardError
240
+ nil
241
+ ensure
242
+ @reader_thr = nil
243
+ end
235
244
 
236
- begin
237
- @stderr_thr&.join(0.5)
238
- rescue StandardError
239
- nil
240
- ensure
241
- @stderr_thr = nil
242
- end
245
+ begin
246
+ @stderr_thr&.join(0.5)
247
+ rescue StandardError
248
+ nil
249
+ ensure
250
+ @stderr_thr = nil
251
+ end
243
252
 
244
- if child_died
245
- hint = stderr_tail.last(5).join(" | ")[0, 512]
246
- Rubik::Log.warn(:mcp, "MCP child process (pid #{exited_pid}) had already exited; recent stderr: #{hint}") unless hint.empty?
247
- end
253
+ if child_died
254
+ hint = stderr_tail.last(5).join(" | ")[0, 512]
255
+ Rubik::Log.warn(:mcp, "MCP child process (pid #{exited_pid}) had already exited; recent stderr: #{hint}") unless hint.empty?
256
+ end
248
257
 
249
- @mutex.synchronize do
250
- @responses.clear
251
- @pending_requests.clear
252
- @cv.broadcast
258
+ @mutex.synchronize do
259
+ @responses.clear
260
+ @pending_requests.clear
261
+ @cv.broadcast
262
+ end
253
263
  end
254
264
  end
255
265
  alias stop close
@@ -299,12 +309,14 @@ module Rubik
299
309
  # semantics need an explicit nil to remove an inherited variable —
300
310
  # leaving the sanitized base plus ONLY the server's explicit env:
301
311
  # entries for anything credential-shaped. Explicit env: entries always
302
- # win in both modes.
312
+ # win in both modes. Credential stripping shares the Platform pattern
313
+ # (single CREDENTIAL_ENV_PATTERN for every spawn path); default mode
314
+ # deliberately leaves credential vars implicit to inherit.
303
315
  def spawn_env
304
316
  base = Rubik::Platform.sanitized_spawn_env
305
317
  unless @inherit_env
306
318
  ENV.each_key do |key|
307
- base[key] = nil if key.match?(CREDENTIAL_ENV_PATTERN)
319
+ base[key] = nil if key.match?(Rubik::Platform::CREDENTIAL_ENV_PATTERN)
308
320
  end
309
321
  end
310
322
  base.merge(
@@ -47,11 +47,12 @@ module Rubik
47
47
  def chronological_summary(max_entries: 20)
48
48
  return "" if @entries.empty?
49
49
 
50
- lines = @entries.first(max_entries).map.with_index(1) do |entry, i|
50
+ lines = @entries.last(max_entries).map.with_index(1) do |entry, i|
51
51
  status_tag = entry[:status] == :error ? " [FAILED]" : ""
52
52
  " #{i}. #{entry[:tool]}#{status_tag}"
53
53
  end
54
- lines << " ... (#{@entries.size - max_entries} more)" if @entries.size > max_entries
54
+ dropped = @entries.size - max_entries
55
+ lines.unshift(" ... (#{dropped} earlier calls omitted)") if dropped.positive?
55
56
  lines.join("\n")
56
57
  end
57
58
 
@@ -97,20 +97,23 @@ module Rubik
97
97
 
98
98
  # ------------------------------------------------------------------
99
99
  # !goal sürücüsü (issue #106): koşu girişi + bütçe-soru döngüsü +
100
- # tek hata kanalı + terminal eşlemesi — start ve resume yollarının
101
- # ORTAK gövdesi. start callable'ı yolu seçer:
102
- # başlangıç → loop.run (taze koşu)
103
- # süreç-içi resume → loop.resume! (history prefix nesne-özdeş)
104
- # çapraz-süreç resume → loop.resume_from (Σ penceresi)
100
+ # Tek hata kanalı + terminal eşlemesi: start ve resume yollarının
101
+ # ORTAK gövdesi. start callable'ı yolu seçer — başlangıç → loop.run,
102
+ # süreç-içi → loop.resume! (prefix nesne-özdeş), çapraz-süreç → resume_from.
105
103
  # Askı dalı (#106): SADECE transient ClientError SUSPENDED'a gider;
106
- # kalıcı hatalar (moderasyon/401/read-timeout) bugünkü fail_goal
107
- # çıktısını bayt-baytına korur.
104
+ # kalıcı hatalar (moderasyon/401/read-timeout) fail_goal çıktısını korur.
108
105
  def drive_goal_turn(ctx, orchestrator:, goal_state:, goal_ledger:,
109
106
  goal_text:, goal_id:, record_pair:, start:)
110
107
  ctx.active_loop = orchestrator
111
108
  begin
112
109
  res = start.call(orchestrator)
113
110
  res = handle_goal_budget_extensions(ctx, orchestrator: orchestrator, goal_state: goal_state, res: res)
111
+ # Truncation is recoverable (issue #613): suspend instead of failing.
112
+ if !res[:ok] && res[:reason] == :output_truncated
113
+ return suspend_goal_turn(ctx, orchestrator: orchestrator, goal_state: goal_state,
114
+ goal_ledger: goal_ledger, goal_text: goal_text, goal_id: goal_id,
115
+ record_pair: record_pair, reason: res[:error], tokens: res[:tokens])
116
+ end
114
117
  rescue Interrupt
115
118
  # ^C hedefi 'running' bırakmasın; eşlenmiş kayıt otursun. Interrupt
116
119
  # yeniden yükselir — kullanıcı mesajını execute_command basar.
@@ -169,13 +172,10 @@ module Rubik
169
172
 
170
173
  def suspend_goal_turn(ctx, orchestrator:, goal_state:, goal_ledger:,
171
174
  goal_text:, goal_id:, record_pair:, reason:, tokens: nil)
175
+ reason = Rubik::Platform.safe_utf8(reason.to_s)
172
176
  attempt = suspended_attempt(ctx, goal_id) + 1
173
- # Ledger kimliği askıdan ÖNCE okunur: suspend! → ledger.suspend!
174
- # sırası metanın bu turun token'larını içermesi için zorunlu,
175
- # ama o damga storage_id'yi değiştirdiği için sonradan atanan id
176
- # SUSPEND_EVENT'e geç kalırdı — ilk askıda kronik satırı slug
177
- # kimliğine düşer, ledger= bağlantısı kaybolurdu.
178
- # resume_cross_process ile aynı uçuş-içi atama önceliği.
177
+ # Ledger id must be read BEFORE suspend!: ledger.suspend! changes
178
+ # storage_id, so a later id misses SUSPEND_EVENT (resume_cross_process order).
179
179
  goal_state.ledger_id = goal_ledger.snapshot[:storage_id] if goal_ledger
180
180
  goal_state.suspend!(reason, tokens: tokens)
181
181
  goal_ledger&.suspend!(suspend_stamp_meta(goal_state, goal_id, reason, attempt))
@@ -185,7 +185,7 @@ module Rubik
185
185
  goal_state: goal_state, ledger: goal_ledger, reason: reason.to_s,
186
186
  suspended_at: Time.now, attempt: attempt
187
187
  ))
188
- ctx.out.puts "\n⏸️ [Rubik::Goal] Suspended after #{goal_state.step_count} steps (transient provider error): #{reason}"
188
+ ctx.out.puts "\n⏸️ [Rubik::Goal] Suspended after #{goal_state.step_count} steps: #{reason}"
189
189
  ctx.out.puts " Loop, counters and Σ ledger are preserved — resume with `!goal resume`."
190
190
  record_pair.call("[Goal suspended after #{goal_state.step_count} steps: #{reason}]", tokens: tokens)
191
191
  end
@@ -179,9 +179,8 @@ module Rubik
179
179
  def continue_loop(extra_steps = 20, plan_only: false, auto: false)
180
180
  # run()'ın ensure'i eski alt bağlamı imha etti; resume_turn! ile aynı
181
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
182
+ # kur — ResumeWindow tek home (#475 disiplini), koşu sonunda imha et.
183
+ resume_window.reopen_context!
185
184
  begin
186
185
  subagent_notice_inbox.keep_for_continuation # retention seam: SubagentNoticeInbox#keep_for_continuation
187
186
  extend_budget(extra_steps)
@@ -199,7 +198,7 @@ module Rubik
199
198
  @history << { role: "user", content: continuation_msg }
200
199
  execute_steps(opts: opts, plan_only: plan_only)
201
200
  ensure
202
- @loop_context&.dispose
201
+ resume_window.close_context!
203
202
  end
204
203
  end
205
204
 
@@ -254,9 +253,9 @@ module Rubik
254
253
  def resume_turn!(reason: "llm_error_recovery", on_step: nil)
255
254
  @on_step = on_step if on_step
256
255
  # run()'ın ensure'i eski alt bağlamı imha etti; taze ctx.extend kur ve
257
- # koşu sonunda imha et (§C scoped sub-context disiplini).
258
- @loop_context&.dispose
259
- @loop_context = @runtime_manager&.context&.extend
256
+ # koşu sonunda imha et (§C scoped sub-context disiplini — ResumeWindow
257
+ # üzerinden, tek home).
258
+ resume_window.reopen_context!
260
259
  begin
261
260
  # Plan 61 D-14 mold: marker kendi user mesajı olarak gider.
262
261
  @history << { role: "user", content: "<turn_resumed reason=\"#{Rubik::Platform.xml_escape(reason.to_s)[0, 300]}\" " \
@@ -264,7 +263,7 @@ module Rubik
264
263
  "Resuming the SAME task with full context and step budget preserved. Continue working toward completion.\" />" }
265
264
  execute_steps(opts: resume_request_opts)
266
265
  ensure
267
- @loop_context&.dispose
266
+ resume_window.close_context!
268
267
  @loop_context = nil
269
268
  end
270
269
  end
@@ -285,13 +284,13 @@ module Rubik
285
284
  default
286
285
  end
287
286
 
288
- # Turn-result contract (public: the TurnExecutor user-channel adapter
289
- # builds every terminal through it, and the shell drives
290
- # continue_loop off the carried loop_instance).
291
- def turn_result(success:, error: nil, output: nil)
287
+ # Turn-result contract (public: the user-channel adapter builds every
288
+ # terminal through it; the shell drives continue_loop off loop_instance).
289
+ def turn_result(success:, error: nil, output: nil, reason: nil)
292
290
  r = { ok: success, steps: @step_count, tokens: @total_tokens, streamed: @last_turn_streamed == true, loop_instance: self }
293
291
  r[:output] = output if output
294
292
  r[:error] = error if error
293
+ r[:reason] = reason if reason
295
294
  r
296
295
  end
297
296
 
@@ -14,18 +14,28 @@ module Rubik
14
14
  # (zararsız sıralama).
15
15
  module CompletionSupervisor
16
16
  def handle_subagent_completion(inst)
17
- merge_branch_buffer(inst) if inst.workspace == "branch" && inst.completed?
18
- auto_apply_subagent_buffer(inst) if inst.completed?
19
- retain_result(inst)
20
- Rubik::Storage::TranscriptIndexer.index(storage_store, inst)
21
- reap_orphans
22
- release_ready!
23
- emit_completion_notice(inst)
24
- notify_wait!
17
+ guard_completion_step("branch buffer merge", inst) { merge_branch_buffer(inst) if inst.workspace == "branch" && inst.completed? }
18
+ guard_completion_step("auto-apply", inst) { auto_apply_subagent_buffer(inst) if inst.completed? }
19
+ guard_completion_step("result retention", inst) { retain_result(inst) }
20
+ guard_completion_step("transcript indexing", inst) { Rubik::Storage::TranscriptIndexer.index(storage_store, inst) }
21
+ guard_completion_step("orphan reaping", inst) { reap_orphans }
22
+ guard_completion_step("ready release", inst) { release_ready! }
23
+ ensure
24
+ # The terminal contract (issue #619): never strand a waiter.
25
+ guard_completion_step("completion notice", inst) { emit_completion_notice(inst) }
26
+ guard_completion_step("waiter wake-up", inst) { notify_wait! }
25
27
  end
26
28
 
27
29
  private
28
30
 
31
+ # One failing step degrades to a warning; the rest of the choreography still runs.
32
+ def guard_completion_step(label, inst)
33
+ yield
34
+ rescue StandardError => e
35
+ Rubik::Log.warn(:orchestrator, "completion #{label} failed for #{inst.id}: #{e.class}: #{e.message}")
36
+ nil
37
+ end
38
+
29
39
  # One terminal outcome per execution (issue #125): an operator kill
30
40
  # already announced the cancellation from the kill path — the settle
31
41
  # notice would be a duplicate. Natural settles announce here, with the
@@ -125,9 +125,13 @@ module Rubik
125
125
  cm.absorb_partial_rows!(@deps.history)
126
126
  @deps.history << { role: "assistant", content: accumulated }
127
127
  end
128
+ # The buffered text now lives in history as one row. Flush the
129
+ # manager so a resumed run neither duplicates it nor re-inherits an
130
+ # exhausted strike count (issue #613: truncation is resumable).
131
+ cm.reset!
128
132
 
129
133
  @deps.on_step&.call(type: :error, content: trunc_action[:error], step: @deps.step_count, max_steps: @deps.max_steps)
130
- @deps.loop_instance.turn_result(success: false, error: trunc_action[:error])
134
+ @deps.loop_instance.turn_result(success: false, error: trunc_action[:error], reason: :output_truncated)
131
135
  end
132
136
 
133
137
  # ── nudge texts ──