rubik 0.15.0 → 0.15.2

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 9a391892bea3be5bbf6d2102c6800ed7c728c253e4f6f003a7765e6b727b51ef
4
- data.tar.gz: cf65a2aa159ce1c0ce5765a1aeedda43467a46e918ac7bb4e921e812fbd4edf5
3
+ metadata.gz: 3893e544a1045fe7b5f65d210b6c0fa4fbbcfe119237997859b61a1fc2ff0e5a
4
+ data.tar.gz: 1aceb9d392428d4bdf54af394769fba31e49a32a22e8cbd00b9926776553627c
5
5
  SHA512:
6
- metadata.gz: 44fc9d447ea49d37e7c6483a61b69755aa882acaf8b446fd660e6a60d973566be865675dd49f555a2795ce2d6f3e09ceb990da67c514a9f4aebff4b28bf86f14
7
- data.tar.gz: 5c65c0f28f82e7e8feac9cc4b7f849192c48ed81a4a256f17db687d0eb780783593ba00bc25e21e4f3902d7e47e9bed4df56671508ff3e38bfd0a236980c7e16
6
+ metadata.gz: 9d94ca34c36f594888fd10dabd19a5149b7136afe4c9ed6523a4d0e2586db830f794ca07270ea8dd6f44b31329466230a969eaf2861053d4ac47f2ae23ba698b
7
+ data.tar.gz: da41db479dcde1beaeace5c684f8e67daf84400518303d4a6dd086042e2b4ad6b6f37d08dd49e6e902ef32a42483a3588b458889c9b21d1dc9ee6789891b6213
data/CHANGELOG.md CHANGED
@@ -8,6 +8,52 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
8
8
 
9
9
  ## [Unreleased]
10
10
 
11
+ ## [0.15.2] - 2026-11-23
12
+
13
+ The suspend-and-redact patch: output-token truncation suspends a goal
14
+ instead of failing it, container driver output joins the redaction
15
+ pipeline — and three refactors collapse duplicated spawn-env, loop-context
16
+ and LSP-delegation patterns behind single seams.
17
+
18
+ ### Fixed
19
+
20
+ - **Goals suspend instead of failing on output-token truncation (#614):**
21
+ reaching the auto-continue ceiling while producing a large report used to
22
+ fail the goal terminally. The truncation is now tagged terminal with
23
+ `:output_truncated` and routed through the existing transient-error
24
+ suspend path, so the goal is resumable with its loop, counters and ledger
25
+ preserved; the continuation buffer flushes at the terminal so a resumed
26
+ turn neither duplicates the stitched partial nor re-inherits exhausted
27
+ strikes. A charset-less provider error body is also sanitized at
28
+ `suspend_goal_turn` entry (the suspend path had the same
29
+ `Encoding::CompatibilityError` gap the fail path had).
30
+ - **Container driver output is redacted (#615):** Docker, podman and
31
+ bubblewrap drivers passed stdout/stderr/output through unredacted while
32
+ ProcessDriver always redacted — a credential printed inside a container
33
+ reached model-visible output unmasked. Result assembly now funnels through
34
+ `Base#finalize_result`; podman also gains the named container +
35
+ timeout force-remove cleanup docker already had, and redundant guard
36
+ deduplication is dropped.
37
+
38
+ ## [0.15.1] - 2026-11-20
39
+
40
+ The subagent-report-rescue patch: a report turn whose reasoning spends the
41
+ whole output budget is no longer thrown away — the channel continues the
42
+ turn instead of counting it empty, and salvages partial text rather than
43
+ failing silently.
44
+
45
+ ### Fixed
46
+
47
+ - **Subagent reports survive output-budget truncation (#610):** the
48
+ subagent channel ignored `finish_reason=length`, so a report turn whose
49
+ reasoning spent the whole budget was counted as an empty response and
50
+ died on the second strike, losing the report. The channel now reuses
51
+ `ContinuationManager` to continue with a targeted nudge, stitches partial
52
+ text across continuations, raises the per-request output cap (bounded)
53
+ after a truncated turn, and salvages the last assistant message as a
54
+ clearly marked result when the continue ceiling is exhausted — instead of
55
+ an empty failure.
56
+
11
57
  ## [0.15.0] - 2026-11-20
12
58
 
13
59
  The diagnostics-and-hardening minor: the LSP client learns pull diagnostics
@@ -1939,7 +1985,9 @@ installation section.
1939
1985
  - Context: serialized index mutations, snapshot-outside-lock reconcile,
1940
1986
  streaming-first truncation.
1941
1987
 
1942
- [Unreleased]: https://github.com/ozgurulukir/rubik/compare/v0.15.0...HEAD
1988
+ [Unreleased]: https://github.com/ozgurulukir/rubik/compare/v0.15.2...HEAD
1989
+ [0.15.2]: https://github.com/ozgurulukir/rubik/compare/v0.15.1...v0.15.2
1990
+ [0.15.1]: https://github.com/ozgurulukir/rubik/compare/v0.15.0...v0.15.1
1943
1991
  [0.15.0]: https://github.com/ozgurulukir/rubik/compare/v0.14.0...v0.15.0
1944
1992
  [0.14.0]: https://github.com/ozgurulukir/rubik/compare/v0.13.0...v0.14.0
1945
1993
  [0.13.0]: https://github.com/ozgurulukir/rubik/compare/v0.12.0...v0.13.0
@@ -40,6 +40,13 @@ module Rubik
40
40
  # lsp_diagnostics tool from ever hanging on a wedged server.
41
41
  DIAGNOSTIC_PULL_TIMEOUT = 5
42
42
 
43
+ # The snapshot shape returned when no running client holds the
44
+ # document — one home shared by Client rescue paths and the Manager's
45
+ # inactive fallbacks, so the contract gains a key once, not 4×.
46
+ UNAVAILABLE_SNAPSHOT = {
47
+ state: :unavailable, diagnostics: [].freeze, document_version: nil, published_version: nil
48
+ }.freeze
49
+
43
50
  attr_reader :language, :server_cmd, :root_dir, :server_capabilities,
44
51
  :sync_capabilities
45
52
  # The JSON-RPC transport delegate (issue #470). Exposed read-only as a
@@ -329,7 +336,7 @@ module Rubik
329
336
  refresh_diagnostics_via_pull(abs_path) if pull_diagnostics? && snapshot[:state] == :pending
330
337
  snapshot
331
338
  rescue ArgumentError, TypeError
332
- { state: :unavailable, diagnostics: [], document_version: nil, published_version: nil }
339
+ UNAVAILABLE_SNAPSHOT
333
340
  end
334
341
 
335
342
  def wait_for_diagnostics(file_path, timeout: 0.2)
@@ -343,7 +350,7 @@ module Rubik
343
350
  @document_store.diagnostic_snapshot(abs_path)[:state] == :pending
344
351
  @document_store.await_diagnostics(abs_path, timeout)
345
352
  rescue ArgumentError, TypeError
346
- { state: :unavailable, diagnostics: [], document_version: nil, published_version: nil }
353
+ UNAVAILABLE_SNAPSHOT
347
354
  end
348
355
 
349
356
  def all_diagnostic_snapshots
@@ -197,33 +197,30 @@ module Rubik
197
197
  def sync_buffer_file(file_path, content)
198
198
  return false unless enabled?
199
199
 
200
- client = client_for(file_path)
201
- return false unless client&.running
202
-
203
- # Try did_change, or did_open if not yet opened
204
- if client.document_open?(file_path)
205
- client.did_change(file_path, content)
206
- else
207
- client.did_open(file_path, content, document_language_id(file_path))
200
+ with_running_client(file_path, ->(_client) { false }) do |client|
201
+ # Try did_change, or did_open if not yet opened
202
+ if client.document_open?(file_path)
203
+ client.did_change(file_path, content)
204
+ else
205
+ client.did_open(file_path, content, document_language_id(file_path))
206
+ end
208
207
  end
209
208
  end
210
209
 
211
210
  def did_save_file(file_path, content = nil)
212
211
  return false unless enabled?
213
212
 
214
- client = client_for(file_path)
215
- return false unless client&.running
216
-
217
- client.did_save(file_path, content)
213
+ with_running_client(file_path, ->(_client) { false }) do |client|
214
+ client.did_save(file_path, content)
215
+ end
218
216
  end
219
217
 
220
218
  def did_close_file(file_path)
221
219
  return false unless enabled?
222
220
 
223
- client = client_for(file_path)
224
- return false unless client&.running
225
-
226
- client.did_close(file_path)
221
+ with_running_client(file_path, ->(_client) { false }) do |client|
222
+ client.did_close(file_path)
223
+ end
227
224
  end
228
225
 
229
226
  def sync_buffer_file_if_needed(file_path, buffer_manager)
@@ -257,24 +254,21 @@ module Rubik
257
254
  end
258
255
 
259
256
  def diagnostics_for(file_path)
260
- client = client_for(file_path)
261
- return [] unless client&.running
262
-
263
- client.diagnostics_for(file_path)
257
+ with_running_client(file_path, ->(_client) { [] }) do |client|
258
+ client.diagnostics_for(file_path)
259
+ end
264
260
  end
265
261
 
266
262
  def diagnostics_snapshot_for(file_path)
267
- client = client_for(file_path)
268
- return { state: :unavailable, diagnostics: [], document_version: nil, published_version: nil } unless client&.running
269
-
270
- client.diagnostics_snapshot_for(file_path)
263
+ with_running_client(file_path, ->(_client) { Client::UNAVAILABLE_SNAPSHOT }) do |client|
264
+ client.diagnostics_snapshot_for(file_path)
265
+ end
271
266
  end
272
267
 
273
268
  def wait_for_diagnostics(file_path, timeout: 0.2)
274
- client = client_for(file_path)
275
- return { state: :unavailable, diagnostics: [], document_version: nil, published_version: nil } unless client&.running
276
-
277
- client.wait_for_diagnostics(file_path, timeout: timeout)
269
+ with_running_client(file_path, ->(_client) { Client::UNAVAILABLE_SNAPSHOT }) do |client|
270
+ client.wait_for_diagnostics(file_path, timeout: timeout)
271
+ end
278
272
  end
279
273
 
280
274
  def all_diagnostics
@@ -316,24 +310,21 @@ module Rubik
316
310
  end
317
311
 
318
312
  def hover(file_path, line, character)
319
- client = client_for(file_path)
320
- return { ok: false, error: inactive_client_error(file_path, client) } unless client&.running
321
-
322
- client.hover(file_path, line, character)
313
+ with_running_client(file_path, ->(client) { { ok: false, error: inactive_client_error(file_path, client) } }) do |client|
314
+ client.hover(file_path, line, character)
315
+ end
323
316
  end
324
317
 
325
318
  def definition(file_path, line, character)
326
- client = client_for(file_path)
327
- return { ok: false, error: inactive_client_error(file_path, client) } unless client&.running
328
-
329
- client.definition(file_path, line, character)
319
+ with_running_client(file_path, ->(client) { { ok: false, error: inactive_client_error(file_path, client) } }) do |client|
320
+ client.definition(file_path, line, character)
321
+ end
330
322
  end
331
323
 
332
324
  def references(file_path, line, character)
333
- client = client_for(file_path)
334
- return { ok: false, error: inactive_client_error(file_path, client) } unless client&.running
335
-
336
- client.references(file_path, line, character)
325
+ with_running_client(file_path, ->(client) { { ok: false, error: inactive_client_error(file_path, client) } }) do |client|
326
+ client.references(file_path, line, character)
327
+ end
337
328
  end
338
329
 
339
330
  def status_summary
@@ -498,6 +489,18 @@ module Rubik
498
489
  @recovery_errors[lang] || "LSP not active for '#{file_path}'"
499
490
  end
500
491
  end
492
+
493
+ # One running-client funnel for the file-scoped delegation methods:
494
+ # resolves the client and yields it while running; otherwise calls the
495
+ # fallback lambda with the (possibly nil) client. The fallback owns the
496
+ # per-method inactive shape (false, [], the unavailable snapshot, the
497
+ # hover-error hash) so observable outputs stay byte-identical.
498
+ def with_running_client(file_path, fallback)
499
+ client = client_for(file_path)
500
+ return fallback.call(client) unless client&.running
501
+
502
+ yield client
503
+ end
501
504
  end
502
505
  end
503
506
  end
@@ -22,13 +22,6 @@ module Rubik
22
22
  # Errno::EPIPE after this many seconds instead of a deadlock.
23
23
  STDIN_WRITE_TIMEOUT = 5.0
24
24
 
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
25
  attr_reader :command, :args, :env, :inherit_env, :root_dir, :running, :wait_thr
33
26
 
34
27
  def initialize(command, args: [], env: {}, inherit_env: true, root_dir: Dir.pwd, guard: nil)
@@ -299,12 +292,14 @@ module Rubik
299
292
  # semantics need an explicit nil to remove an inherited variable —
300
293
  # leaving the sanitized base plus ONLY the server's explicit env:
301
294
  # entries for anything credential-shaped. Explicit env: entries always
302
- # win in both modes.
295
+ # win in both modes. Credential stripping shares the Platform pattern
296
+ # (single CREDENTIAL_ENV_PATTERN for every spawn path); default mode
297
+ # deliberately leaves credential vars implicit to inherit.
303
298
  def spawn_env
304
299
  base = Rubik::Platform.sanitized_spawn_env
305
300
  unless @inherit_env
306
301
  ENV.each_key do |key|
307
- base[key] = nil if key.match?(CREDENTIAL_ENV_PATTERN)
302
+ base[key] = nil if key.match?(Rubik::Platform::CREDENTIAL_ENV_PATTERN)
308
303
  end
309
304
  end
310
305
  base.merge(
@@ -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
 
@@ -50,6 +50,15 @@ module Rubik
50
50
  :context_limit, :max_output_tokens, :config, :pause_facts, :prompt_reconstructible,
51
51
  :run_seq, :journal, :operations
52
52
 
53
+ # Grows the per-request output cap after a truncated turn (issue
54
+ # #610) so reasoning + the final report can both fit. Monotonic and
55
+ # bounded by `ceiling`; never lowers a cap the operator set higher.
56
+ def raise_max_output_tokens!(ceiling)
57
+ grown = [@max_output_tokens * 2, ceiling].min
58
+ @max_output_tokens = grown if grown > @max_output_tokens
59
+ @max_output_tokens
60
+ end
61
+
53
62
  # Budget delegation: step counters live in Subagent::Budget (reader contract preserved).
54
63
  def current_step = @budget.current_step
55
64
  def max_steps = @budget.max_steps
@@ -2,6 +2,7 @@
2
2
 
3
3
  require_relative "../tool_call_id"
4
4
  require_relative "../tool_history"
5
+ require_relative "../continuation_manager"
5
6
 
6
7
  module Rubik
7
8
  module Orchestrator
@@ -11,6 +12,14 @@ module Rubik
11
12
  # the channel never holds @monitor and never emits on the bus under
12
13
  # it (the same discipline as the StepRunner methods it replaces).
13
14
  class SubagentChannel < Channel
15
+ # Prefixed to results rebuilt from history after the model went silent.
16
+ SALVAGE_NOTICE = "[Salvaged: the model returned no final report. This is the last assistant " \
17
+ "message from the run; see the transcript for the full work.]"
18
+
19
+ # Output-cap growth bound for truncated turns (issue #610); the
20
+ # operator's own llm.default_max_output_tokens still wins if higher.
21
+ MAX_OUTPUT_TOKENS_CEILING = 16_384
22
+
14
23
  def initialize(instance)
15
24
  super()
16
25
  @inst = instance
@@ -63,8 +72,37 @@ module Rubik
63
72
  @inst.journal&.record_token_usage(run: @inst.run_seq, usage: usage)
64
73
  end
65
74
 
66
- # Deferred: subagent continuation is future work.
67
- def handle_truncation(_res, _text, _tool_calls, _finish_reason) = nil
75
+ # Stitches the continuation buffer (partial texts from earlier
76
+ # finish_reason=length cycles) in front of the current text, so a
77
+ # long final report cut off mid-way is delivered whole (issue #610).
78
+ def final_text(res, text)
79
+ return text if continuation_manager.continuation_buffer.empty?
80
+
81
+ raw = res.respond_to?(:text) ? res.text : text
82
+ continuation_manager.stitch_and_reset(Platform.safe_utf8(raw).to_s, history: @inst.history)
83
+ end
84
+
85
+ # Same truncation flow as the user channel (issue #610): reasoning
86
+ # that spent the whole output budget gets a targeted continuation
87
+ # nudge instead of the generic empty-response strike. When the
88
+ # auto-continue ceiling is exhausted (or disabled) the partial text
89
+ # already produced is salvaged as the result; with nothing to
90
+ # salvage the turn fails with the actionable diagnostic.
91
+ def handle_truncation(res, text_resp, tool_calls, finish_reason)
92
+ cm = continuation_manager
93
+ return nil unless cm.truncation?(finish_reason)
94
+
95
+ raw_text = res.respond_to?(:text) ? res.text : text_resp
96
+ safe_text = Platform.safe_utf8(raw_text).to_s
97
+ action = cm.handle_truncation(
98
+ finish_reason: finish_reason, text_resp: safe_text, tool_calls: tool_calls, res: res,
99
+ max_tokens: @inst.max_output_tokens || 4096
100
+ )
101
+ return continue_truncated(action) if action[:continue]
102
+ return nil unless action[:error]
103
+
104
+ salvage_or_fail(cm, safe_text, action[:error])
105
+ end
68
106
 
69
107
  # ── announce ──
70
108
  def announce_compaction(reason, layer)
@@ -74,12 +112,27 @@ module Rubik
74
112
  def announce_llm_thought(_text, **) = nil
75
113
 
76
114
  # ── terminals & dispatch ──
115
+ def continuation_manager
116
+ @continuation_manager ||= ContinuationManager.new(config: @inst.config)
117
+ end
118
+
77
119
  # The shared two-strike nudge policy (Channel#empty_response_turn)
78
120
  # now governs empty, tool-less responses: one standard nudge row,
79
121
  # then the terminal below on the second consecutive strike. The
80
122
  # subagent can no longer "complete" with an empty result — the
81
123
  # declared Phase 4 delta.
124
+ #
125
+ # Second consecutive empty strike: the run's work is already in
126
+ # history, so deliver the last assistant text as a clearly marked
127
+ # salvaged result instead of an empty failure (issue #610). With
128
+ # nothing to salvage the turn still fails.
82
129
  def empty_response_failure
130
+ salvaged = last_assistant_text
131
+ if salvaged
132
+ continuation_manager.reset!
133
+ return final_text_result("#{SALVAGE_NOTICE}\n\n#{salvaged}")
134
+ end
135
+
83
136
  @inst.fail_turn!("Empty response from model (2 consecutive)")
84
137
  { ok: false, completed: false }
85
138
  end
@@ -119,6 +172,42 @@ module Rubik
119
172
  @inst.execute_subagent_tool_call(tool_call)
120
173
  nil
121
174
  end
175
+
176
+ private
177
+
178
+ def last_assistant_text
179
+ row = @inst.history.reverse_each.find do |m|
180
+ m.is_a?(Hash) && m[:role] == "assistant" && !m[:content].to_s.strip.empty?
181
+ end
182
+ row && row[:content].to_s.strip
183
+ end
184
+
185
+ def continue_truncated(action)
186
+ nudge_policy.reset!
187
+ if [:thinking_exhausted, :text_truncated].include?(action[:scenario]) && @inst.respond_to?(:raise_max_output_tokens!)
188
+ @inst.raise_max_output_tokens!(MAX_OUTPUT_TOKENS_CEILING)
189
+ end
190
+ if action[:thought]
191
+ @inst.history << { role: "assistant", content: nil, thought: Platform.safe_utf8(action[:thought]) }
192
+ elsif action[:partial_text]
193
+ @inst.history << { role: "assistant", content: action[:partial_text] }
194
+ end
195
+ @inst.history << { role: "user", content: action[:nudge] }
196
+ :consumed
197
+ end
198
+
199
+ def salvage_or_fail(manager, current_text, error)
200
+ accumulated = manager.continuation_buffer + current_text
201
+ if accumulated.strip.empty?
202
+ manager.reset!
203
+ @inst.fail_turn!(error)
204
+ return { ok: false, completed: false }
205
+ end
206
+
207
+ manager.absorb_partial_rows!(@inst.history)
208
+ manager.reset!
209
+ final_text_result(accumulated.strip)
210
+ end
122
211
  end
123
212
  end
124
213
  end
@@ -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 ──
@@ -20,6 +20,19 @@ module Rubik
20
20
  "echo", "dir", "cd", "cls", "set", "type", "copy", "move", "del", "md", "rd", "exit", "rem", "ver", "vol"
21
21
  ].freeze
22
22
 
23
+ # Credential-shaped variable names stripped from child-process
24
+ # environments (issue #586). Matching is by underscore-delimited
25
+ # segment (case-insensitive) so OPENAI_API_KEY, MY_SECRET and
26
+ # AWS_ACCESS_KEY_ID are covered without matching words like
27
+ # "tokenizer". NOTE: integrity hygiene, NOT a confinement boundary.
28
+ # Defined at module level (not inside class << self) so every spawn
29
+ # path can reference Rubik::Platform::CREDENTIAL_ENV_PATTERN directly.
30
+ CREDENTIAL_ENV_PATTERN = /
31
+ (?:_|\A)(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|PAT|CREDENTIALS?)(?:_|\z)
32
+ |\A(?:DATABASE|REDIS|MONGO|POSTGRES|MYSQL|AMQP)_URL\z
33
+ |_(?:DATABASE|REDIS|CONNECTION)_URL\z
34
+ /ix
35
+
23
36
  class << self
24
37
  # Audit 1: gated debug logging for the platform layer's many intentional
25
38
  # rescue-and-fallback paths (UTF-8 sanitation, atomic writes). Follows
@@ -61,25 +74,12 @@ module Rubik
61
74
  env
62
75
  end
63
76
 
64
- # Credential-shaped variable names stripped from child-process
65
- # environments (issue #586). Matching is by underscore-delimited
66
- # segment (case-insensitive) so OPENAI_API_KEY, MY_SECRET and
67
- # AWS_ACCESS_KEY_ID are covered without matching words like
68
- # "tokenizer". NOTE: integrity hygiene, NOT a confinement boundary.
69
- CREDENTIAL_ENV_PATTERN = /
70
- (?:_|\A)(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|PAT|CREDENTIALS?)(?:_|\z)
71
- |\A(?:DATABASE|REDIS|MONGO|POSTGRES|MYSQL|AMQP)_URL\z
72
- |_(?:DATABASE|CONNECTION)_URL\z
73
- /ix
74
-
75
77
  # sanitized_spawn_env plus an explicit nil for every credential-shaped
76
78
  # host variable (spawn semantics: nil UNSETs it; benign variables stay
77
79
  # out of the hash and remain normally inheritable). Consumers:
78
- # TaskManager#start (issue #586) and Driver::ProcessDriver#child_env
79
- # (both now delegate here — single shared CREDENTIAL_ENV_PATTERN).
80
- # The MCP stdio transport keeps its own narrower pattern on purpose:
81
- # it matches _REDIS_URL, which this pattern's underscore-URL branch
82
- # does not, so this pattern is not a safe superset for that path.
80
+ # TaskManager#start (issue #586), Driver::ProcessDriver#child_env, and
81
+ # the MCP stdio transport's inherit_env: false path — one shared
82
+ # CREDENTIAL_ENV_PATTERN for every spawn path.
83
83
  def credential_free_env
84
84
  env = sanitized_spawn_env
85
85
  ENV.each_key do |key|
@@ -40,9 +40,8 @@ module Rubik
40
40
  # shared session guard via driver_opts (options[:guard]) so operator
41
41
  # policy — the live command allowlist above all — applies to every
42
42
  # driver; the lazy local fallback (silent audit, zero policy) serves
43
- # only standalone / test-constructed drivers. ProcessDriver keeps its
44
- # own copy with cmd.exe refinements; container drivers re-verify the
45
- # raw command through this shared helper before spawning.
43
+ # only standalone / test-constructed drivers. Every driver re-verifies
44
+ # the raw command through this shared helper before spawning.
46
45
  def guard
47
46
  @options[:guard] || (@guard ||= Rubik::Security::Guard.new(audit_log_path: nil))
48
47
  end
@@ -54,6 +53,30 @@ module Rubik
54
53
  true
55
54
  end
56
55
 
56
+ # Assemble the driver result with output hygiene applied uniformly:
57
+ # stdout/stderr are redacted and `output` is recomputed from the
58
+ # redacted parts, so a credential a command prints can never reach
59
+ # model-visible output through any driver. Every driver funnels its
60
+ # result through this one home.
61
+ # NOTE: integrity hygiene, NOT a secret-confinement boundary.
62
+ def finalize_result(res, driver: name, stderr: nil, extra: {})
63
+ require_relative "../../security/redactor" unless defined?(Rubik::Security::Redactor)
64
+ stdout = Rubik::Security::Redactor.redact(res[:stdout])
65
+ stderr = Rubik::Security::Redactor.redact(stderr || res[:stderr])
66
+ {
67
+ ok: res[:ok],
68
+ exit_code: res[:exit_code],
69
+ # Explicit timeout flag plumbed to the tool layer (#597-3).
70
+ timed_out: res[:timed_out] == true,
71
+ stdout: stdout,
72
+ stderr: stderr,
73
+ output: [stdout, stderr].reject(&:empty?).join("\n"),
74
+ duration: res[:duration],
75
+ driver: driver,
76
+ **extra
77
+ }
78
+ end
79
+
57
80
  # Issue #591: bind-mount every configured allowed dir read-write,
58
81
  # mirroring BubblewrapDriver's loop, so commands legitimately touching
59
82
  # an allowed external dir work identically across drivers.
@@ -38,6 +38,11 @@ module Rubik
38
38
  end
39
39
 
40
40
  def run(cmd, timeout: 15, chdir: Dir.pwd, allow_network: false, memory_limit_mb: 512, cpus: "1.0") # rubocop:disable Lint/UnusedMethodArgument
41
+ # Defense-in-depth: re-run the shared session guard before spawning,
42
+ # the same way the docker/podman/process drivers do, so a caller
43
+ # that forgot its own pre-check is still gated by operator policy.
44
+ verify_command_safety!(cmd)
45
+
41
46
  workspace = File.expand_path(chdir)
42
47
 
43
48
  bwrap_cmd = ["bwrap"]
@@ -72,17 +77,7 @@ module Rubik
72
77
  error_message: "Bubblewrap execution error"
73
78
  )
74
79
 
75
- {
76
- ok: res[:ok],
77
- exit_code: res[:exit_code],
78
- # Explicit timeout flag plumbed to the tool layer (#597-3).
79
- timed_out: res[:timed_out] == true,
80
- stdout: res[:stdout],
81
- stderr: res[:stderr],
82
- output: res[:output],
83
- duration: res[:duration],
84
- driver: "bwrap"
85
- }
80
+ finalize_result(res)
86
81
  end
87
82
 
88
83
  # Probe the installed bwrap once. bubblewrap's --tmpfs has only ever
@@ -58,17 +58,7 @@ module Rubik
58
58
  Rubik::Log.warn(:sandbox, "docker container '#{container_name}' could not be removed") unless removed
59
59
  end
60
60
 
61
- {
62
- ok: res[:ok],
63
- exit_code: res[:exit_code],
64
- # Explicit timeout flag plumbed to the tool layer (#597-3).
65
- timed_out: res[:timed_out] == true,
66
- stdout: res[:stdout],
67
- stderr: res[:stderr],
68
- output: res[:output],
69
- duration: res[:duration],
70
- driver: "docker"
71
- }
61
+ finalize_result(res, driver: "docker")
72
62
  end
73
63
  end
74
64
  end
@@ -2,8 +2,10 @@
2
2
 
3
3
  require_relative "base"
4
4
  require_relative "../../platform"
5
+ require_relative "../../log"
5
6
  require "open3"
6
7
  require "timeout"
8
+ require "securerandom"
7
9
 
8
10
  module Rubik
9
11
  module Sandbox
@@ -23,9 +25,11 @@ module Rubik
23
25
 
24
26
  image = @options[:image] || DEFAULT_IMAGE
25
27
  workspace = File.expand_path(chdir)
28
+ container_name = "rubik-box-#{SecureRandom.hex(6)}"
26
29
 
27
30
  podman_args = [
28
31
  "podman", "run", "--rm",
32
+ "--name", container_name,
29
33
  *CONTAINER_HARDENING_FLAGS,
30
34
  "-w", "/workspace",
31
35
  "-v", "#{workspace}:/workspace:rw",
@@ -38,25 +42,29 @@ module Rubik
38
42
  podman_args.push("--network", "none") unless allow_network
39
43
  podman_args.push(image, "sh", "-c", cmd)
40
44
 
41
- res = Rubik::Platform.popen_capture(
42
- *podman_args,
43
- timeout: timeout,
44
- chdir: workspace,
45
- timeout_message: "Podman sandbox execution timed out after #{timeout} seconds",
46
- error_message: "Podman sandbox error"
47
- )
45
+ res = begin
46
+ Rubik::Platform.popen_capture(
47
+ *podman_args,
48
+ timeout: timeout,
49
+ chdir: workspace,
50
+ timeout_message: "Podman sandbox execution timed out after #{timeout} seconds",
51
+ error_message: "Podman sandbox error"
52
+ )
53
+ ensure
54
+ # Mirror DockerDriver: the watchdog kills the podman client process
55
+ # tree on timeout, and --rm removal is performed by that client, so
56
+ # a timed-out run would otherwise orphan the container. Only a
57
+ # killed run needs the force-remove — a completed run (any exit
58
+ # code) already removed itself via --rm, and rm-ing a missing
59
+ # container would just warn noise. Best-effort cleanup; a failed
60
+ # `podman rm -f` leaves a trace.
61
+ if res.nil? || res[:timed_out] == true
62
+ removed = system("podman", "rm", "-f", container_name, out: File::NULL, err: File::NULL)
63
+ Rubik::Log.warn(:sandbox, "podman container '#{container_name}' could not be removed") unless removed
64
+ end
65
+ end
48
66
 
49
- {
50
- ok: res[:ok],
51
- exit_code: res[:exit_code],
52
- # Explicit timeout flag plumbed to the tool layer (#597-3).
53
- timed_out: res[:timed_out] == true,
54
- stdout: res[:stdout],
55
- stderr: res[:stderr],
56
- output: res[:output],
57
- duration: res[:duration],
58
- driver: "podman"
59
- }
67
+ finalize_result(res, driver: "podman")
60
68
  end
61
69
  end
62
70
  end
@@ -39,23 +39,12 @@ module Rubik
39
39
  )
40
40
 
41
41
  stderr_out = resolved[:note] ? "#{resolved[:note]}\n#{res[:stderr]}" : res[:stderr]
42
- require_relative "../../security/redactor" unless defined?(Rubik::Security::Redactor)
43
- clean_stdout = Rubik::Security::Redactor.redact(res[:stdout])
44
- clean_stderr = Rubik::Security::Redactor.redact(stderr_out)
45
42
 
46
- {
47
- ok: res[:ok],
48
- exit_code: res[:exit_code],
49
- # Explicit timeout flag plumbed to the tool layer (#597-3): a
50
- # legitimate timeout(1) exit 124 must not read as a runner kill.
51
- timed_out: res[:timed_out] == true,
52
- stdout: clean_stdout,
53
- stderr: clean_stderr,
54
- output: [clean_stdout, clean_stderr].reject(&:empty?).join("\n"),
55
- duration: res[:duration],
56
- driver: "process",
57
- shell: resolved[:shell]
58
- }
43
+ finalize_result(
44
+ res,
45
+ stderr: stderr_out,
46
+ extra: { shell: resolved[:shell] }
47
+ )
59
48
  end
60
49
 
61
50
  private
@@ -133,23 +122,6 @@ module Rubik
133
122
  raise_dangerous(cmd.to_s, rule_name: "cmd.exe_construct")
134
123
  end
135
124
 
136
- # Security guard gating cmd.exe spawns. The Runner injects the shared
137
- # session guard via driver_opts (options[:guard]) so operator policy —
138
- # the live command allowlist above all — applies here too; the lazy
139
- # local fallback (silent audit, zero policy) serves only standalone /
140
- # test-constructed drivers.
141
- def guard
142
- @options[:guard] || (@guard ||= Rubik::Security::Guard.new(audit_log_path: nil))
143
- end
144
-
145
- # Re-run the security guard's classification, scoped to the given shell
146
- # so cmd.exe semantics are enforced when spawned via cmd. Blocks a
147
- # POSIX-safe-but-cmd-dangerous command with BlockedWriteError.
148
- def verify_command_safety!(cmd, shell: nil)
149
- guard.verify_command_safety!(cmd, shell: shell)
150
- true
151
- end
152
-
153
125
  # Raise the standard BlockedWriteError used throughout the guard
154
126
  # surface for an explicitly detected dangerous construct.
155
127
  def raise_dangerous(cmd, rule_name:)
data/lib/rubik/version.rb CHANGED
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Rubik
4
- VERSION = "0.15.0"
4
+ VERSION = "0.15.2"
5
5
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: rubik
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.15.0
4
+ version: 0.15.2
5
5
  platform: ruby
6
6
  authors:
7
7
  - Özgür Ulukır