rubik 0.14.0 → 0.15.1

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 +109 -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 +31 -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 +112 -7
  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
@@ -33,6 +33,13 @@ module Rubik
33
33
  "vue" => "vue-language-server --stdio"
34
34
  }.freeze
35
35
 
36
+ # Bounds every textDocument/diagnostic pull. The reader thread of the
37
+ # pull answers through the transport's response correlation; if the
38
+ # server stalls, the pull times out here, the snapshot stays :pending,
39
+ # and waiters fall through their own bounded timeout. Keeps the
40
+ # lsp_diagnostics tool from ever hanging on a wedged server.
41
+ DIAGNOSTIC_PULL_TIMEOUT = 5
42
+
36
43
  attr_reader :language, :server_cmd, :root_dir, :server_capabilities,
37
44
  :sync_capabilities
38
45
  # The JSON-RPC transport delegate (issue #470). Exposed read-only as a
@@ -70,6 +77,17 @@ module Rubik
70
77
  source: :not_advertised, open_close: false, change: 0,
71
78
  save: false, include_text: false
72
79
  }.freeze
80
+ # Populated from the initialize response (see start): true when the
81
+ # server advertises `diagnosticProvider`, meaning diagnostics must be
82
+ # pulled via textDocument/diagnostic instead of (or in addition to)
83
+ # push publishDiagnostics.
84
+ @pull_diagnostics = false
85
+ # In-flight pull registry: path -> document version the outstanding
86
+ # textDocument/diagnostic request was issued for. Doubles as a
87
+ # dedupe guard (one pull per path+version) so polling loops cannot
88
+ # spawn unbounded threads.
89
+ @pull_in_flight = {}
90
+ @pull_mutex = Mutex.new
73
91
  end
74
92
 
75
93
  def binary_name
@@ -92,6 +110,7 @@ module Rubik
92
110
  @document_store.reset
93
111
  end
94
112
  @transport.reset_correlation
113
+ @pull_mutex.synchronize { @pull_in_flight.clear }
95
114
 
96
115
  cmd_parts = @server_argv.dup
97
116
  bin = cmd_parts.first
@@ -136,6 +155,7 @@ module Rubik
136
155
 
137
156
  @server_capabilities = init_res.is_a?(Hash) ? (init_res["capabilities"] || {}) : {}
138
157
  @sync_capabilities = normalize_sync_capabilities(@server_capabilities["textDocumentSync"])
158
+ @pull_diagnostics = pull_diagnostics_advertised?(@server_capabilities)
139
159
  unless send_notification("initialized", {})
140
160
  stop
141
161
  return false
@@ -189,6 +209,7 @@ module Rubik
189
209
  # unwinds the graceful shutdown: kill_tree is the only thing that can
190
210
  # unblock a writer parked on a full stdin pipe.
191
211
  @transport.shutdown
212
+ @pull_mutex.synchronize { @pull_in_flight.clear }
192
213
  end
193
214
  end
194
215
  alias dispose stop
@@ -222,14 +243,16 @@ module Rubik
222
243
  @document_store.commit(abs_path) do
223
244
  version = @document_store.next_version
224
245
  @document_store.stage_version(abs_path, content, version)
225
- send_notification("textDocument/didOpen", {
226
- textDocument: {
227
- uri: document_uri(abs_path),
228
- languageId: language_id.to_s,
229
- version: version,
230
- text: content
231
- }
232
- })
246
+ sent = send_notification("textDocument/didOpen", {
247
+ textDocument: {
248
+ uri: document_uri(abs_path),
249
+ languageId: language_id.to_s,
250
+ version: version,
251
+ text: content
252
+ }
253
+ })
254
+ send_pull_diagnostics_unlocked(abs_path, version) if sent && pull_diagnostics?
255
+ sent
233
256
  end
234
257
  end
235
258
  rescue StandardError => e
@@ -302,13 +325,22 @@ module Rubik
302
325
 
303
326
  def diagnostics_snapshot_for(file_path)
304
327
  abs_path = normalized_document_path(file_path)
305
- @document_store.diagnostic_snapshot(abs_path)
328
+ snapshot = @document_store.diagnostic_snapshot(abs_path)
329
+ refresh_diagnostics_via_pull(abs_path) if pull_diagnostics? && snapshot[:state] == :pending
330
+ snapshot
306
331
  rescue ArgumentError, TypeError
307
332
  { state: :unavailable, diagnostics: [], document_version: nil, published_version: nil }
308
333
  end
309
334
 
310
335
  def wait_for_diagnostics(file_path, timeout: 0.2)
311
336
  abs_path = normalized_document_path(file_path)
337
+ # Issue a pull whenever a pull-capable server has the document open
338
+ # and we do not yet hold a versioned answer for its current version
339
+ # (:pending) — repeated calls for an already-answered version are
340
+ # deduplicated by the in-flight registry, and :fresh results from a
341
+ # combined push+pull server are returned as-is (freshest data wins).
342
+ refresh_diagnostics_via_pull(abs_path) if pull_diagnostics? && @document_store.open?(abs_path) &&
343
+ @document_store.diagnostic_snapshot(abs_path)[:state] == :pending
312
344
  @document_store.await_diagnostics(abs_path, timeout)
313
345
  rescue ArgumentError, TypeError
314
346
  { state: :unavailable, diagnostics: [], document_version: nil, published_version: nil }
@@ -318,8 +350,147 @@ module Rubik
318
350
  @document_store.all_diagnostic_snapshots
319
351
  end
320
352
 
353
+ # Workspace-wide pull refresh (issue #583): re-issue pulls for every
354
+ # document whose snapshot is still :pending. Bounded by the pull
355
+ # timeout on the client side and by the caller's wait on the tool
356
+ # side; a wedged server leaves snapshots :pending rather than
357
+ # hanging the surface.
358
+ def refresh_pending_diagnostic_snapshots
359
+ return unless pull_diagnostics?
360
+
361
+ @document_store.all_diagnostic_snapshots.each do |path, snapshot|
362
+ refresh_diagnostics_via_pull(path) if snapshot[:state] == :pending
363
+ end
364
+ nil
365
+ end
366
+
321
367
  private
322
368
 
369
+ # ---- Pull diagnostics (issue #583). Servers that advertise
370
+ # ---- `diagnosticProvider` (e.g. typeprof, the DEFAULT ruby server,
371
+ # ---- with ruby-lsp the configured fallback) never push
372
+ # ---- publishDiagnostics; without an explicit textDocument/diagnostic
373
+ # ---- request the document stays :pending forever and every
374
+ # ---- diagnostics surface reports nothing. Pulls ride the
375
+ # ---- transport's own request correlation: send_request blocks its
376
+ # ---- own thread until the response is matched, so no response can
377
+ # ---- dead-letter, and results are version-guarded on apply so a
378
+ # ---- stale async pull can never clobber a newer snapshot.
379
+
380
+ def pull_diagnostics?
381
+ @pull_diagnostics == true
382
+ end
383
+
384
+ # diagnosticProvider may be a boolean or an options object.
385
+ def pull_diagnostics_advertised?(capabilities)
386
+ provider = capabilities["diagnosticProvider"]
387
+ provider == true || provider.is_a?(Hash)
388
+ end
389
+
390
+ # Fire-and-forget pull, called with @document_mutex held (didOpen /
391
+ # didChange paths). Deduplicated per (path, version) so tight polling
392
+ # loops (diagnostics_snapshot_for) cannot spawn unbounded threads.
393
+ def send_pull_diagnostics_unlocked(abs_path, version)
394
+ return false unless alive?
395
+ return false if @pull_mutex.synchronize { @pull_in_flight[abs_path] == version }
396
+
397
+ @pull_mutex.synchronize { @pull_in_flight[abs_path] = version }
398
+ uri = document_uri(abs_path)
399
+ Thread.new do
400
+ result = @transport.send_request(
401
+ "textDocument/diagnostic",
402
+ { textDocument: { uri: uri } },
403
+ timeout: DIAGNOSTIC_PULL_TIMEOUT
404
+ )
405
+ apply_pull_diagnostics_result(abs_path, version, result)
406
+ rescue StandardError => e
407
+ # Timeout / transport failure: the snapshot simply stays :pending
408
+ # and waiters fall through their bounded timeout. Never raise
409
+ # out of an unowned thread.
410
+ Rubik::Log.warn(:lsp, "diagnostic pull failed for #{abs_path}: #{e.class}: #{e.message}")
411
+ ensure
412
+ @pull_mutex.synchronize do
413
+ @pull_in_flight.delete(abs_path) if @pull_in_flight[abs_path] == version
414
+ end
415
+ end
416
+ true
417
+ end
418
+
419
+ # Refresh entry used by wait_for_diagnostics / diagnostics_snapshot_for
420
+ # when the snapshot is still :pending (covers lost or timed-out pulls).
421
+ def refresh_diagnostics_via_pull(abs_path)
422
+ @document_mutex.synchronize do
423
+ return unless @document_store.open?(abs_path)
424
+
425
+ version = @document_store.version_for(abs_path)
426
+ send_pull_diagnostics_unlocked(abs_path, version) if version
427
+ end
428
+ nil
429
+ rescue StandardError => e
430
+ Rubik::Log.warn(:lsp, "diagnostic refresh failed for #{abs_path}: #{e.class}: #{e.message}")
431
+ nil
432
+ end
433
+
434
+ # Applies a textDocument/diagnostic response. Non-hash results carry
435
+ # no items to install; `kind: "unchanged"` confirms previously recorded
436
+ # diagnostics remain valid for the current document version. Payloads are
437
+ # applied only when the document still sits at the pulled version, so
438
+ # stale async results (a slow server answering after a further edit) are
439
+ # discarded instead of clobbering the newer snapshot. relatedDocuments
440
+ # entries (cross-file diagnostics for OTHER documents, issue #585) are
441
+ # recorded through the same version-guarded path; entries for documents
442
+ # rubik never opened are skipped without erroring.
443
+ def apply_pull_diagnostics_result(abs_path, pulled_version, result)
444
+ return unless result.is_a?(Hash)
445
+
446
+ @document_mutex.synchronize do
447
+ current = @document_store.version_for(abs_path)
448
+ return unless current == pulled_version
449
+
450
+ if result["kind"] == "unchanged"
451
+ existing = @document_store.diagnostic_snapshot(abs_path)[:diagnostics]
452
+ @document_store.record_diagnostics(abs_path, existing, current)
453
+ else
454
+ items = result["items"].is_a?(Array) ? result["items"] : []
455
+ @document_store.record_diagnostics(abs_path, items, current)
456
+ end
457
+
458
+ record_related_documents(result["relatedDocuments"])
459
+ end
460
+ nil
461
+ rescue StandardError => e
462
+ Rubik::Log.warn(:lsp, "diagnostic pull result dropped for #{abs_path}: #{e.class}: #{e.message}")
463
+ nil
464
+ end
465
+
466
+ # Records cross-file diagnostics from a pull response's relatedDocuments
467
+ # map (DocumentUri -> diagnostic report, issue #585). Each entry goes
468
+ # through the same version-guarded record_diagnostics path as the pulled
469
+ # document; documents rubik never opened (or closed since) are skipped
470
+ # without erroring — a pull response may legitimately reference files
471
+ # outside this client's document store.
472
+ def record_related_documents(related)
473
+ return unless related.is_a?(Hash)
474
+
475
+ related.each do |uri, report|
476
+ next unless report.is_a?(Hash)
477
+
478
+ begin
479
+ raw_path = Rubik::Platform.from_file_uri(uri)
480
+ path = normalized_document_path(raw_path)
481
+ next unless @document_store.open?(path)
482
+
483
+ version = @document_store.version_for(path)
484
+ next unless version
485
+
486
+ items = report["items"].is_a?(Array) ? report["items"] : []
487
+ @document_store.record_diagnostics(path, items, version)
488
+ rescue StandardError => e
489
+ Rubik::Log.warn(:lsp, "relatedDocument entry skipped for #{uri}: #{e.class}: #{e.message}")
490
+ end
491
+ end
492
+ end
493
+
323
494
  # ---- Delegates to the transport (issue #470). These thin shims keep
324
495
  # ---- the Client's internal call sites and per-instance test stubs
325
496
  # ---- working unchanged; the implementations live on Transport.
@@ -433,21 +604,65 @@ module Rubik
433
604
  return false unless @document_store.open?(abs_path)
434
605
  return true if @document_store.content_for(abs_path) == content
435
606
 
607
+ old_content = @document_store.content_for(abs_path)
436
608
  @document_store.commit(abs_path) do
437
609
  version = @document_store.next_version
438
610
  @document_store.stage_version(abs_path, content, version)
439
- send_notification("textDocument/didChange", {
440
- textDocument: {
441
- uri: document_uri(abs_path),
442
- version: version
443
- },
444
- # A text-only event is a full-document replacement,
445
- # which is valid for both Full and Incremental sync.
446
- contentChanges: [{ text: content }]
447
- })
611
+ sent = send_notification("textDocument/didChange", {
612
+ textDocument: {
613
+ uri: document_uri(abs_path),
614
+ version: version
615
+ },
616
+ contentChanges: build_content_changes(old_content, content)
617
+ })
618
+ send_pull_diagnostics_unlocked(abs_path, version) if sent && pull_diagnostics?
619
+ sent
448
620
  end
449
621
  end
450
622
 
623
+ # Spec 3.17: Full sync (kind 1) replaces the whole document with a
624
+ # range-less change event. Incremental sync (kind 2) REQUIRES a range —
625
+ # a range-less event is invalid there, and servers that honor the spec
626
+ # (e.g. typeprof, the default ruby server) drop or misapply it. For
627
+ # incremental servers we send ONE edit spanning the entire OLD document,
628
+ # which is semantically a full replacement but structurally spec-valid.
629
+ # Character offsets are UTF-16 code units per the LSP spec.
630
+ def build_content_changes(old_content, new_content)
631
+ return [{ text: new_content }] unless @sync_capabilities[:change].to_i == 2
632
+ return [{ text: new_content }] if old_content.nil?
633
+
634
+ old_content = old_content.to_s
635
+ [{
636
+ range: {
637
+ start: { line: 0, character: 0 },
638
+ end: end_position_for(old_content)
639
+ },
640
+ text: new_content
641
+ }]
642
+ end
643
+
644
+ # LSP Position for the exclusive end of content: last line index and
645
+ # the line's length in UTF-16 code units (the spec's offset unit —
646
+ # Ruby String#length counts characters, which diverges for astral-plane
647
+ # code points that encode as surrogate pairs). Empty or nil content
648
+ # resolves to line 0 character 0 (preventing invalid negative line indices).
649
+ def end_position_for(content)
650
+ return { line: 0, character: 0 } if content.nil? || content.empty?
651
+
652
+ lines = content.split(/\r\n|\n|\r/, -1)
653
+ last_line = [lines.length - 1, 0].max
654
+ last_text = lines.last.to_s
655
+ { line: last_line, character: utf16_length(last_text) }
656
+ end
657
+
658
+ def utf16_length(text)
659
+ str = text.to_s
660
+ str = str.encode("UTF-16LE", invalid: :replace, undef: :replace) unless str.encoding == Encoding::UTF_16LE
661
+ str.bytesize / 2
662
+ rescue StandardError
663
+ text.to_s.length
664
+ end
665
+
451
666
  def normalize_sync_capabilities(value)
452
667
  case value
453
668
  when Numeric
@@ -63,6 +63,12 @@ module Rubik
63
63
  @document_contents[path]
64
64
  end
65
65
 
66
+ # The version the server currently knows for an open document, nil
67
+ # when the document is not open. Callers hold the document mutex.
68
+ def version_for(path)
69
+ @open_documents[path]
70
+ end
71
+
66
72
  def next_version
67
73
  @version_counter += 1
68
74
  end
@@ -301,6 +301,20 @@ module Rubik
301
301
  result
302
302
  end
303
303
 
304
+ # Re-issues textDocument/diagnostic pulls for every document still
305
+ # pending (issue #583). Delegates per client; bounded by the client's
306
+ # pull timeout so this can never hang the caller.
307
+ def refresh_pending_diagnostic_snapshots
308
+ @monitor.synchronize do
309
+ @clients.each_value do |client|
310
+ next unless client.running
311
+
312
+ client.refresh_pending_diagnostic_snapshots
313
+ end
314
+ end
315
+ nil
316
+ end
317
+
304
318
  def hover(file_path, line, character)
305
319
  client = client_for(file_path)
306
320
  return { ok: false, error: inactive_client_error(file_path, client) } unless client&.running
@@ -38,6 +38,12 @@ module Rubik
38
38
  # prevent the kill_tree that unblocks the pipe.
39
39
  WRITE_TIMEOUT = 5.0
40
40
 
41
+ # Upper bound on a single framed message the reader accepts (issue #601).
42
+ # A wedged/corrupt server emitting a garbage oversized Content-Length
43
+ # would otherwise park the reader thread on a blocking read of that many
44
+ # bytes. 16 MiB is far above any legitimate LSP payload.
45
+ MAX_FRAME_SIZE = 16 * 1024 * 1024
46
+
41
47
  attr_reader :mutex, :cv, :running
42
48
 
43
49
  def initialize(root_dir:, on_message:)
@@ -331,6 +337,17 @@ module Rubik
331
337
 
332
338
  break if content_length.nil?
333
339
 
340
+ # Issue #601: a non-positive or oversized wire-supplied
341
+ # Content-Length means corrupt framing — fail the reader
342
+ # instead of parking on an unbounded blocking read.
343
+ if content_length <= 0 || content_length > MAX_FRAME_SIZE
344
+ @mutex.synchronize do
345
+ @reader_failure = "LSP server sent invalid Content-Length: #{content_length} " \
346
+ "(must be > 0 and <= #{MAX_FRAME_SIZE})"
347
+ end
348
+ break
349
+ end
350
+
334
351
  body = @stdout.read(content_length)
335
352
  break unless body
336
353
 
@@ -16,6 +16,16 @@ module Rubik
16
16
  class ContinuationManager
17
17
  TRUNCATION_REASONS = ["length", "max_tokens"].freeze
18
18
 
19
+ # The continuation nudges handle_truncation appends right after each
20
+ # partial row; they anchor absorb_partial_rows! to the genuine partial
21
+ # positions (issue #595-1 follow-up). Keep in sync with the nudge
22
+ # strings inside handle_truncation.
23
+ NUDGE_PREFIXES = [
24
+ "Your thinking process reached the output token limit",
25
+ "Your previous response was cut off",
26
+ "Your tool call was cut off"
27
+ ].freeze
28
+
19
29
  attr_reader :auto_continue_count, :continuation_buffer, :max_auto_continues
20
30
 
21
31
  def initialize(config: nil, max_auto_continues: nil)
@@ -23,6 +33,10 @@ module Rubik
23
33
  @max_auto_continues = (max_auto_continues || safe_config("llm.max_auto_continues", 3)).to_i
24
34
  @auto_continue_count = 0
25
35
  @continuation_buffer = +""
36
+ # The exact partial texts appended to history per text-truncation
37
+ # cycle (issue #595-1): the stitch/failure paths absorb their
38
+ # assistant rows so the history carries the full text ONCE.
39
+ @partial_texts = []
26
40
  end
27
41
 
28
42
  def enabled?
@@ -94,6 +108,7 @@ module Rubik
94
108
  }
95
109
  when :text_truncated
96
110
  @continuation_buffer << text_resp.to_s
111
+ @partial_texts << text_resp.to_s
97
112
  {
98
113
  continue: true,
99
114
  scenario: :text_truncated,
@@ -114,8 +129,12 @@ module Rubik
114
129
  end
115
130
 
116
131
  # Stitches any accumulated continuation buffer with the final response
117
- # text and resets the continuation state.
118
- def stitch_and_reset(final_text)
132
+ # text and resets the continuation state. When `history` is given, the
133
+ # partial assistant rows appended per continuation cycle are absorbed
134
+ # FIRST (issue #595-1): the stitched full text replaces them instead
135
+ # of duplicating every partial.
136
+ def stitch_and_reset(final_text, history: nil)
137
+ absorb_partial_rows!(history) if history
119
138
  stitched = if @continuation_buffer.empty?
120
139
  final_text.to_s
121
140
  else
@@ -125,9 +144,42 @@ module Rubik
125
144
  stitched
126
145
  end
127
146
 
147
+ # Absorbs the partial assistant rows recorded across continuation
148
+ # cycles out of the given history (issue #595-1/#595-2). Anchoring
149
+ # (#595-1 follow-up): a partial row is always the assistant row
150
+ # immediately preceding its own continuation nudge, so matching is
151
+ # restricted to that position — content equality alone would also
152
+ # delete an unrelated earlier assistant row that coincidentally
153
+ # repeats a partial verbatim.
154
+ def absorb_partial_rows!(history)
155
+ @partial_texts.each do |partial|
156
+ history.each_index do |i|
157
+ row = history[i]
158
+ next unless row.is_a?(Hash)
159
+ next unless continuation_nudge_row?(history[i + 1])
160
+
161
+ role = row[:role] || row["role"]
162
+ tool_calls = row[:tool_calls] || row["tool_calls"]
163
+ content = row[:content] || row["content"]
164
+ history[i] = nil if role == "assistant" && tool_calls.nil? && content == partial
165
+ end
166
+ history.compact!
167
+ end
168
+ end
169
+
170
+ # The continuation nudges appended right after each partial row are
171
+ # the anchor markers (handle_truncation is the only writer).
172
+ def continuation_nudge_row?(row)
173
+ return false unless row.is_a?(Hash)
174
+
175
+ content = (row[:content] || row["content"]).to_s
176
+ (row[:role] || row["role"]) == "user" && NUDGE_PREFIXES.any? { |prefix| content.start_with?(prefix) }
177
+ end
178
+
128
179
  def reset!
129
180
  @auto_continue_count = 0
130
181
  @continuation_buffer = +""
182
+ @partial_texts = []
131
183
  end
132
184
 
133
185
  # A successful turn closes the *consecutive* truncation chain, so the
@@ -274,7 +274,7 @@ module Rubik
274
274
 
275
275
  def resume_in_process(ctx, entry)
276
276
  ctx.recorder&.record_user_turn("!goal resume")
277
- # Kaynaklama (issue #454): canlı girdiden; resume! geçişi (SUSPENDED → RUNNING) kaynaklamanın parçası.
277
+ # Kaynaklama (issue #454): resume! geçişi (SUSPENDED → RUNNING) kaynaklamanın parçası.
278
278
  goal_state = entry.goal_state
279
279
  goal_ledger = entry.ledger
280
280
  goal_state.resume!
@@ -491,23 +491,23 @@ module Rubik
491
491
  end
492
492
  private_class_method :build_goal_orchestrator
493
493
 
494
- # Damga meta'sındaki suspended_at (iso8601) → Time; bozuk değer
495
- # nil — Loop#append_resume_marker! "unknown" downtime basar.
494
+ # suspended_at (iso8601) → Time; bozuk değer nil — marker "unknown" basar.
496
495
  def parse_suspended_at(value)
497
496
  Time.iso8601(value.to_s)
498
497
  rescue ArgumentError, TypeError
499
498
  nil
500
499
  end
501
500
 
502
- # Defense-in-depth behind the loop-level goal guard: if a success
503
- # terminal escapes GoalWait with live subagent units, the goal must
504
- # stop honestly instead of celebrating a false completion. Fails
505
- # CONSERVATIVE: coeffect absence is nil-safe (Coeffects.get never
506
- # raises for a missing subsystem), so a raise here is real breakage
507
- # — reporting zero would launder it into exactly the false
508
- # "Goal Achieved" this backstop exists to refuse.
501
+ # Defense-in-depth behind the loop-level goal guard: a success terminal
502
+ # that escapes GoalWait over live units must stop honestly, not celebrate.
503
+ # Fails CONSERVATIVE: coeffect absence is nil-safe, so a raise is real
504
+ # breakage — zero would launder it into the false "Goal Achieved".
509
505
  def goal_active_subagent_count(ctx)
510
506
  supervisor = Rubik::Coeffects.get(ctx.runtime_manager&.context, Rubik::Coeffects::SUBAGENT_SUPERVISOR)
507
+ # Issue #594: dispatched_count covers :budget_exhausted units parked
508
+ # mid-task; doubles predating it still answer through active_count.
509
+ return supervisor.dispatched_count.to_i if supervisor.respond_to?(:dispatched_count)
510
+
511
511
  supervisor&.active_count.to_i
512
512
  rescue StandardError => e
513
513
  Rubik::Log.warn(:orchestrator, "goal completion defense could not inspect subagents " \
@@ -21,16 +21,22 @@ module Rubik
21
21
  @deps = deps
22
22
  end
23
23
 
24
- # Live dispatched work: any active unit (running, paused on error or
25
- # budget, or blocked on an ask_question answer) counts — none of them
26
- # may be abandoned by a completion. A nil supervisor (no subagent
27
- # system, bare test loops) means nothing is pending.
24
+ # Live dispatched work: any in-flight unit (running, paused on error
25
+ # or budget, parked at :budget_exhausted, or blocked on an
26
+ # ask_question answer) counts — none of them may be abandoned by a
27
+ # completion (issue #594: :budget_exhausted is parked mid-task, not
28
+ # finished). A nil supervisor (no subagent system, bare test loops)
29
+ # means nothing is pending. Test-double supervisors that predate
30
+ # dispatched_count still answer through active_count.
28
31
  def pending?
29
- active_count.positive?
32
+ dispatched_count.positive?
30
33
  end
31
34
 
32
- def active_count
33
- supervisor&.active_count.to_i
35
+ def dispatched_count
36
+ sup = supervisor
37
+ return sup.dispatched_count.to_i if sup.respond_to?(:dispatched_count)
38
+
39
+ sup&.active_count.to_i
34
40
  end
35
41
 
36
42
  # Called by the user channel INSTEAD of building the success
@@ -43,7 +49,7 @@ module Rubik
43
49
  return inject_notices! unless inbox.empty?
44
50
 
45
51
  timeout = wait_timeout
46
- @deps.on_step&.call(type: :goal_wait, via: via, active: active_count, timeout: timeout,
52
+ @deps.on_step&.call(type: :goal_wait, via: via, active: dispatched_count, timeout: timeout,
47
53
  step: @deps.step_count, max_steps: @deps.max_steps)
48
54
  # Notices arriving while the model was concluding sit in the inbox;
49
55
  # wait_for blocks until the whole dispatched set settles (budget-
@@ -98,7 +104,7 @@ module Rubik
98
104
  # falsely completing.
99
105
  def timeout_nudge!
100
106
  append_user_message!(
101
- "<goal_wait_timeout active=\"#{active_count}\" timeout=\"#{wait_timeout}\">#{active_count} dispatched " \
107
+ "<goal_wait_timeout active=\"#{dispatched_count}\" timeout=\"#{wait_timeout}\">#{dispatched_count} dispatched " \
102
108
  "subagent(s) are still running. The goal is NOT complete while they run. Conclude your turn again to " \
103
109
  "keep waiting, or inspect and steer them (`manage_subagents` action 'status' | 'wait' | 'kill'). " \
104
110
  "Call finish only once every dispatched subagent has settled.</goal_wait_timeout>"