rubik 0.7.1 → 0.8.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 (78) hide show
  1. checksums.yaml +4 -4
  2. data/ATTRIBUTION.md +1 -1
  3. data/CHANGELOG.md +205 -1
  4. data/lib/rubik/ast/typescript_extractor.rb +2 -2
  5. data/lib/rubik/config/deep_ops.rb +14 -0
  6. data/lib/rubik/config/defaults.rb +5 -4
  7. data/lib/rubik/config/env_loader.rb +88 -0
  8. data/lib/rubik/config/model_catalog.rb +13 -0
  9. data/lib/rubik/config/pruner.rb +34 -0
  10. data/lib/rubik/config/schema.rb +163 -0
  11. data/lib/rubik/config/scoped.rb +108 -0
  12. data/lib/rubik/config/store.rb +19 -8
  13. data/lib/rubik/config.rb +129 -53
  14. data/lib/rubik/diagnostics/parser.rb +2 -2
  15. data/lib/rubik/kernel/dispatcher.rb +19 -23
  16. data/lib/rubik/kernel/init.rb +22 -18
  17. data/lib/rubik/orchestrator/goal_ledger/ledger.rb +3 -9
  18. data/lib/rubik/orchestrator/goal_ledger/observation_projection.rb +3 -9
  19. data/lib/rubik/orchestrator/step_executor.rb +12 -59
  20. data/lib/rubik/orchestrator/subagent/deferred_spec.rb +51 -2
  21. data/lib/rubik/orchestrator/subagent/dependency.rb +20 -20
  22. data/lib/rubik/orchestrator/subagent/execution_reads.rb +1 -1
  23. data/lib/rubik/orchestrator/subagent/journal.rb +3 -9
  24. data/lib/rubik/orchestrator/subagent/lifecycle.rb +10 -1
  25. data/lib/rubik/orchestrator/subagent/paging.rb +49 -0
  26. data/lib/rubik/orchestrator/subagent/reaper.rb +1 -3
  27. data/lib/rubik/orchestrator/subagent/redeploy_transaction.rb +99 -0
  28. data/lib/rubik/orchestrator/subagent/result_archive.rb +12 -22
  29. data/lib/rubik/orchestrator/subagent/reuse.rb +37 -31
  30. data/lib/rubik/orchestrator/subagent/scoped_registry.rb +14 -23
  31. data/lib/rubik/orchestrator/subagent/spawn_transaction.rb +13 -3
  32. data/lib/rubik/orchestrator/subagent/supervisor.rb +6 -2
  33. data/lib/rubik/orchestrator/subagent/task_ownership.rb +2 -2
  34. data/lib/rubik/orchestrator/subagent/tool_dispatch.rb +12 -49
  35. data/lib/rubik/orchestrator/subagent/transcript_reader.rb +14 -13
  36. data/lib/rubik/orchestrator/turn_executor.rb +9 -4
  37. data/lib/rubik/repl/commands/subagents.rb +3 -2
  38. data/lib/rubik/repl/commands/workspace.rb +14 -8
  39. data/lib/rubik/repl/lifecycle.rb +11 -0
  40. data/lib/rubik/repl/pruner/service.rb +4 -9
  41. data/lib/rubik/repl/service_catalog.rb +2 -1
  42. data/lib/rubik/runtime/context.rb +6 -1
  43. data/lib/rubik/runtime/fiber.rb +17 -5
  44. data/lib/rubik/runtime/manager.rb +19 -12
  45. data/lib/rubik/sandbox/runner.rb +28 -13
  46. data/lib/rubik/storage/layout.rb +14 -3
  47. data/lib/rubik/storage/render.rb +1 -1
  48. data/lib/rubik/storage/vakanuvis/distill_gate.rb +3 -3
  49. data/lib/rubik/storage/vakanuvis/harness.rb +4 -65
  50. data/lib/rubik/storage/vakanuvis/orientation.rb +1 -2
  51. data/lib/rubik/storage/vakanuvis/recall.rb +84 -0
  52. data/lib/rubik/storage/vakanuvis.rb +1 -0
  53. data/lib/rubik/tools/base.rb +65 -0
  54. data/lib/rubik/tools/builtins/define_subagent.rb +6 -0
  55. data/lib/rubik/tools/builtins/dmesg.rb +5 -5
  56. data/lib/rubik/tools/builtins/exec.rb +1 -2
  57. data/lib/rubik/tools/builtins/files.rb +19 -25
  58. data/lib/rubik/tools/builtins/goal_ledger.rb +2 -2
  59. data/lib/rubik/tools/builtins/grep.rb +8 -8
  60. data/lib/rubik/tools/builtins/interactive.rb +7 -3
  61. data/lib/rubik/tools/builtins/lifecycle.rb +2 -1
  62. data/lib/rubik/tools/builtins/lsp.rb +2 -2
  63. data/lib/rubik/tools/builtins/pruner.rb +2 -2
  64. data/lib/rubik/tools/builtins/runtime.rb +1 -1
  65. data/lib/rubik/tools/builtins/send_message.rb +20 -3
  66. data/lib/rubik/tools/builtins/skill.rb +1 -1
  67. data/lib/rubik/tools/builtins/storage.rb +1 -1
  68. data/lib/rubik/tools/builtins/subagent.rb +14 -1
  69. data/lib/rubik/tools/builtins/subagent_lifecycle.rb +5 -3
  70. data/lib/rubik/tools/builtins/symbols.rb +4 -4
  71. data/lib/rubik/tools/builtins/task.rb +1 -1
  72. data/lib/rubik/tools/builtins/vakanuvis.rb +2 -2
  73. data/lib/rubik/tools/catalog.rb +19 -0
  74. data/lib/rubik/tools/declaration.rb +15 -2
  75. data/lib/rubik/tools/result_normalizer.rb +115 -0
  76. data/lib/rubik/tools/truncator.rb +3 -3
  77. data/lib/rubik/version.rb +1 -1
  78. metadata +9 -1
@@ -8,6 +8,7 @@ require_relative "tool_circuit_breaker"
8
8
  require_relative "tool_timeout"
9
9
  require_relative "maestro_gate"
10
10
  require_relative "lsp_feedback"
11
+ require_relative "../tools/result_normalizer"
11
12
 
12
13
  module Rubik
13
14
  module Orchestrator
@@ -19,11 +20,10 @@ module Rubik
19
20
  class StepExecutor
20
21
  include MaestroGate
21
22
 
22
- ERROR_PREFIXES = [
23
- "-- ", "Error:", "Error ", "Usage:", "Pre-flight verification failed",
24
- "Bilinmeyen komut", "Failed", "Security blocked", "Command error",
25
- "[EXIT ", "Test run [FAILED]", "Lint [FAILED]", "[CONFLICT]", "[CONFLICT "
26
- ].freeze
23
+ # Single home is Tools::ResultNormalizer; this alias keeps the
24
+ # historical constant address (tests reference it) while the lexicon
25
+ # is owned by the shared normalizer both planes delegate to.
26
+ ERROR_PREFIXES = Rubik::Tools::ResultNormalizer::ERROR_PREFIXES
27
27
 
28
28
  # Plan 87 E-1: state is reached through the ShellDeps façade. Accepts a
29
29
  # bare loop for compatibility with existing test doubles (wrapped).
@@ -46,7 +46,9 @@ module Rubik
46
46
  @deps.on_step&.call(type: :auto_apply, reason: "pre_execution", files: applied, step: @deps.step_count, max_steps: @deps.max_steps)
47
47
  end
48
48
 
49
- return handle_finish_tool(tool_args, text_resp, auto_apply_mode) if canonical_name == "finish"
49
+ finish_call = (tool_instance.respond_to?(:terminal?) && tool_instance.terminal?) ||
50
+ canonical_name == "finish" # unresolved case variant degrades to the name compare
51
+ return handle_finish_tool(tool_args, text_resp, auto_apply_mode) if finish_call
50
52
 
51
53
  # Maestro gate: maestro'nun doğrudan yürütme araçları reddedilir
52
54
  # (detay ve config semantics: maestro_gate.rb).
@@ -185,60 +187,11 @@ module Rubik
185
187
  [raw_output, tool_result]
186
188
  end
187
189
 
190
+ # Thin delegator: carrier classification and truncation limits live in
191
+ # Tools::ResultNormalizer (single home for both orchestrator planes).
188
192
  def normalize_raw_output(raw_output, tool_name, call_id, dur)
189
- max_chars = @deps.shell&.config&.fetch("tools.max_output_chars", Rubik::Tools::Truncator::DEFAULT_MAX_CHARS) || Rubik::Tools::Truncator::DEFAULT_MAX_CHARS
190
- max_lines = @deps.shell&.config&.fetch("tools.max_output_lines", Rubik::Tools::Truncator::DEFAULT_MAX_LINES) || Rubik::Tools::Truncator::DEFAULT_MAX_LINES
191
- trunc_strat = Rubik::Tools::Truncator.resolve_strategy(@deps.shell&.config&.fetch("tools.truncation_strategy", Rubik::Tools::Truncator::DEFAULT_STRATEGY))
192
-
193
- if raw_output.is_a?(Rubik::Tools::Result)
194
- trunc_res = Rubik::Tools::Truncator.truncate(raw_output.output, max_chars: max_chars, max_lines: max_lines, strategy: trunc_strat)
195
- effective_dur = raw_output.duration_ms.positive? ? raw_output.duration_ms : dur
196
- first_line = raw_output.output.lines.first.to_s.strip
197
- first_line = nil if first_line.empty?
198
- Rubik::Tools::Result.new(
199
- tool_name: raw_output.tool_name.to_s.empty? ? tool_name : raw_output.tool_name,
200
- call_id: raw_output.call_id.to_s.empty? ? call_id : raw_output.call_id,
201
- status: raw_output.status, error: raw_output.error || (raw_output.error? ? first_line : nil),
202
- # Structured fields ride along when the tool provides them
203
- # (issue #127): the same Result contract for every carrier.
204
- exit_code: raw_output.exit_code, output: trunc_res[:text], duration_ms: effective_dur,
205
- truncated: raw_output.truncated || trunc_res[:truncated], metadata: raw_output.metadata
206
- )
207
- elsif raw_output.respond_to?(:status) && raw_output.respond_to?(:output)
208
- out_str = raw_output.output.to_s
209
- trunc_res = Rubik::Tools::Truncator.truncate(out_str, max_chars: max_chars, max_lines: max_lines, strategy: trunc_strat)
210
- st = raw_output.status.to_sym
211
- first_line = out_str.lines.first.to_s.strip
212
- first_line = nil if first_line.empty?
213
- err = (raw_output.respond_to?(:error) && raw_output.error) || (st == :error ? first_line : nil)
214
- Rubik::Tools::Result.new(
215
- tool_name: tool_name, call_id: call_id, status: st, error: err, output: trunc_res[:text],
216
- duration_ms: dur, truncated: trunc_res[:truncated],
217
- exit_code: raw_output.respond_to?(:exit_code) ? raw_output.exit_code : nil,
218
- metadata: raw_output.respond_to?(:metadata) ? raw_output.metadata : {}
219
- )
220
- else
221
- out_str = raw_output.to_s
222
- trunc_res = Rubik::Tools::Truncator.truncate(out_str, max_chars: max_chars, max_lines: max_lines, strategy: trunc_strat)
223
-
224
- is_err = if raw_output.respond_to?(:error?)
225
- raw_output.error?
226
- elsif raw_output.respond_to?(:failed?)
227
- raw_output.failed?
228
- elsif raw_output.is_a?(String)
229
- ERROR_PREFIXES.any? { |pfx| raw_output.start_with?(pfx) }
230
- else
231
- false
232
- end
233
-
234
- first_line = out_str.lines.first.to_s.strip
235
- first_line = nil if first_line.empty?
236
-
237
- Rubik::Tools::Result.new(
238
- tool_name: tool_name, call_id: call_id, status: is_err ? :error : :ok,
239
- error: is_err ? first_line : nil, output: trunc_res[:text], duration_ms: dur, truncated: trunc_res[:truncated]
240
- )
241
- end
193
+ Rubik::Tools::ResultNormalizer.normalize(raw_output, tool_name: tool_name, call_id: call_id,
194
+ duration_ms: dur, config: @deps.shell&.config)
242
195
  end
243
196
 
244
197
  def record_circuit_breaker_result(breaker, tool_name, status)
@@ -19,9 +19,22 @@ module Rubik
19
19
  # this spec — nil for explicitly detached work. A cancelled owner makes
20
20
  # the claim loops drop the spec before it ever starts.
21
21
  class DeferredSpec
22
+ class StateError < StandardError; end
23
+
24
+ # The spec machine's every legal from->to edge (Lifecycle family
25
+ # doctrine: one guarded transition per state machine, fail-loud on
26
+ # undeclared edges, same-state idempotent). :cancelled is absorbing —
27
+ # a cancelled spec never re-queues (requeue! refuses) and never
28
+ # re-launches (the claim loops skip it).
29
+ TRANSITIONS = {
30
+ queued: [:spawning, :cancelled],
31
+ spawning: [:queued, :cancelled],
32
+ cancelled: []
33
+ }.transform_values(&:freeze).freeze
34
+
22
35
  attr_reader :id, :parent_id, :role, :type_name, :prompt, :system_prompt,
23
- :workspace, :model, :max_steps, :deps, :provider, :owner
24
- attr_accessor :state, :cancel_reason
36
+ :workspace, :model, :max_steps, :deps, :provider, :owner,
37
+ :state, :cancel_reason
25
38
 
26
39
  def initialize(id:, role:, prompt:, type_name:, deps:, parent_id: ConversationId::ROOT_ID, system_prompt: nil,
27
40
  workspace: "inherit", model: "inherit", max_steps: nil, provider: nil, owner: nil)
@@ -45,6 +58,27 @@ module Rubik
45
58
  def spawning? = @state == :spawning
46
59
  def cancelled? = @state == :cancelled
47
60
 
61
+ # The only mutators (Lifecycle family): the dependency engine claims
62
+ # with mark_spawning!, re-queues a concurrency-refused launch with
63
+ # requeue!, and cancels with cancel! — first reason wins, exactly
64
+ # like TaskCancellation#cancel!. Same-state writes are idempotent
65
+ # no-ops; anything else undeclared raises StateError.
66
+ def mark_spawning!
67
+ transition!(:spawning)
68
+ end
69
+
70
+ def requeue!
71
+ transition!(:queued) unless cancelled?
72
+ end
73
+
74
+ def cancel!(reason)
75
+ return false if cancelled?
76
+
77
+ @cancel_reason = reason.to_s
78
+ transition!(:cancelled)
79
+ true
80
+ end
81
+
48
82
  # Duck-type yüzeyi: render'lar (list/status/wait) Instance ile
49
83
  # DeferredSpec'i AYIRT ETMEDEN kullanır — dallanma yok.
50
84
  def running? = false
@@ -70,6 +104,21 @@ module Rubik
70
104
  started_at: nil, ended_at: nil, transcript: nil, last_error: @cancel_reason,
71
105
  result_summary: nil, result: nil, detached: @owner.nil? }
72
106
  end
107
+
108
+ private
109
+
110
+ # Guarded low-level seam (mirrors Lifecycle#transition!): business
111
+ # callers use the named drivers; illegal edges fail loud with both
112
+ # endpoints in the message. No own lock — every writer already holds
113
+ # the supervisor monitor.
114
+ def transition!(to)
115
+ target = to.to_sym
116
+ return @state if @state == target
117
+
118
+ raise StateError, "illegal DeferredSpec transition #{@id}: #{@state} -> #{target}" unless TRANSITIONS.fetch(@state, []).include?(target)
119
+
120
+ @state = target
121
+ end
73
122
  end
74
123
  end
75
124
  end
@@ -94,13 +94,13 @@ module Rubik
94
94
  # Claim fence: cancellation may land between the entry guard and
95
95
  # this loop — a cancelled owner never launches.
96
96
  if owned_claim_blocked?(spec)
97
- cancel_spec!(spec, "owner task cancelled (^C)")
97
+ spec.cancel!("owner task cancelled (^C)")
98
98
  cancelled << spec
99
99
  next
100
100
  end
101
101
  next unless dependencies_evaluate(spec) == :ready
102
102
 
103
- spec.state = :spawning
103
+ spec.mark_spawning!
104
104
  claimed << spec
105
105
  end
106
106
  end
@@ -130,17 +130,17 @@ module Rubik
130
130
  # to death through the same fixed-point wave as a dead
131
131
  # predecessor.
132
132
  if owned_claim_blocked?(spec)
133
- cancel_spec!(spec, "owner task cancelled (^C)")
133
+ spec.cancel!("owner task cancelled (^C)")
134
134
  wave << spec
135
135
  next
136
136
  end
137
137
 
138
138
  case dependencies_evaluate(spec)
139
139
  when :ready
140
- spec.state = :spawning
140
+ spec.mark_spawning!
141
141
  claimed << spec
142
142
  when :dead
143
- cancel_spec!(spec, "predecessor failed or is no longer tracked")
143
+ spec.cancel!("predecessor failed or is no longer tracked")
144
144
  wave << spec
145
145
  end
146
146
  end
@@ -188,9 +188,9 @@ module Rubik
188
188
  verdicts = spec.deps.map do |d|
189
189
  deferred_pred = @deferred[d[:id]]
190
190
  return :dead if deferred_pred&.cancelled?
191
- return :dead if deferred_pred.nil? && @instances[d[:id]].nil? && (@finished || {})[d[:id]].nil?
191
+ return :dead if deferred_pred.nil? && @instances[d[:id]].nil? && @finished[d[:id]].nil?
192
192
 
193
- inst = @instances[d[:id]] || (@finished || {})[d[:id]]
193
+ inst = @instances[d[:id]] || @finished[d[:id]]
194
194
 
195
195
  if d[:type] == "FS"
196
196
  return :dead if inst&.failed?
@@ -229,12 +229,18 @@ module Rubik
229
229
  inst&.kill if killed_midflight
230
230
  killed_midflight ? [:cancelled, spec] : [:launched, inst]
231
231
  rescue ConcurrencyExceededError
232
- @monitor.synchronize { spec.state = :queued unless spec.cancelled? }
233
- [:queued, spec]
232
+ requeued = false
233
+ @monitor.synchronize do
234
+ requeued = !!spec.requeue!
235
+ end
236
+ # Truthful outcome: a cancelled spec was NOT re-queued — reporting
237
+ # [:queued, ...] made invoke_subagent render "QUEUED" for a spec
238
+ # that will never launch.
239
+ requeued ? [:queued, spec] : [:cancelled, spec]
234
240
  rescue StandardError => e
235
241
  cancelled = nil
236
242
  @monitor.synchronize do
237
- cancel_spec!(spec, "launch failed: #{e.class}: #{e.message}")
243
+ spec.cancel!("launch failed: #{e.class}: #{e.message}")
238
244
  cancelled = spec
239
245
  end
240
246
  announce_cancellations([cancelled])
@@ -253,7 +259,7 @@ module Rubik
253
259
  break if wave.empty?
254
260
 
255
261
  wave.each do |spec|
256
- cancel_spec!(spec, "predecessor failed or is no longer tracked")
262
+ spec.cancel!("predecessor failed or is no longer tracked")
257
263
  cancelled << spec
258
264
  end
259
265
  dead_ids = wave.map(&:id)
@@ -262,11 +268,6 @@ module Rubik
262
268
  cancelled
263
269
  end
264
270
 
265
- def cancel_spec!(spec, reason)
266
- spec.cancel_reason = reason
267
- spec.state = :cancelled
268
- end
269
-
270
271
  def announce_cancellations(specs)
271
272
  specs.each do |spec|
272
273
  Notices.emit(@event_bus, Notices::COMPLETED_EVENT,
@@ -293,7 +294,7 @@ module Rubik
293
294
  def refute_dead_dependencies!(specs)
294
295
  specs.each do |spec|
295
296
  spec.deps.each do |d|
296
- inst = @instances[d[:id]] || (@finished || {})[d[:id]]
297
+ inst = @instances[d[:id]] || @finished[d[:id]]
297
298
  if inst
298
299
  # Tek tüketici: atomlar yeterli — yeni bir Instance
299
300
  # predicate'ine gerek yok (settled? disposed'u dışlar,
@@ -309,7 +310,7 @@ module Rubik
309
310
  end
310
311
 
311
312
  def refute_unknown_dependencies!(specs)
312
- known = @instances.keys + (@finished || {}).keys + @deferred.keys + specs.map(&:id)
313
+ known = @instances.keys + @finished.keys + @deferred.keys + specs.map(&:id)
313
314
  specs.each do |spec|
314
315
  spec.deps.each do |d|
315
316
  next if known.include?(d[:id])
@@ -334,8 +335,7 @@ module Rubik
334
335
  def kill_locked(id, cascade, cancelled)
335
336
  if (spec = @deferred[id])
336
337
  if spec.spawning?
337
- spec.cancel_reason = "killed while launching"
338
- spec.state = :cancelled
338
+ spec.cancel!("killed while launching")
339
339
  else
340
340
  @deferred.delete(id)
341
341
  end
@@ -18,7 +18,7 @@ module Rubik
18
18
  return nil if sid.empty?
19
19
 
20
20
  @monitor.synchronize do
21
- (@instances.values + (@finished || {}).values).find do |inst|
21
+ (@instances.values + @finished.values).find do |inst|
22
22
  inst.respond_to?(:storage_id) && inst.storage_id.to_s == sid
23
23
  end
24
24
  end
@@ -6,6 +6,7 @@ require "time"
6
6
  require "fileutils"
7
7
  require_relative "../../platform"
8
8
  require_relative "../../security/redactor"
9
+ require_relative "../../storage/layout"
9
10
 
10
11
  module Rubik
11
12
  module Orchestrator
@@ -306,15 +307,8 @@ module Rubik
306
307
  value.length > limit ? "#{value[0, limit]}... [truncated #{value.length - limit} chars]" : value
307
308
  end
308
309
 
309
- def config_get(config, key, default)
310
- return default if config.nil?
311
-
312
- val = if config.is_a?(Hash)
313
- config[key] || config.dig(*key.split("."))
314
- elsif config.respond_to?(:fetch)
315
- config.fetch(key, nil)
316
- end
317
- val.nil? ? default : val
310
+ def config_get(config, key, default = nil)
311
+ Rubik::Storage::Layout.config_get(config, key, default)
318
312
  end
319
313
  end
320
314
  end
@@ -38,6 +38,15 @@ module Rubik
38
38
  disposed: []
39
39
  }.transform_values(&:freeze).freeze
40
40
 
41
+ # Attention vocabulary (the tool plane's "needs attention" classification,
42
+ # derived here so a state rename can never silently desync it — the tool
43
+ # layer hand-copied these until now). PARKED_STATES is the vocabulary's
44
+ # own words for the condvar-parked set; ATTENTION_STATES rides
45
+ # :waiting_input on top. A named owned constant, not a computation from
46
+ # TRANSITIONS — no clean derivation from the edges exists.
47
+ PARKED_STATES = [:paused_error, :waiting_budget, :budget_exhausted].freeze
48
+ ATTENTION_STATES = (PARKED_STATES + [:waiting_input]).freeze
49
+
41
50
  # --- Predicates: control-flow questions answer here, not at
42
51
  # consumers. All take the re-entrant monitor; callers composing
43
52
  # them under a held lock pay nothing extra, and external readers
@@ -74,7 +83,7 @@ module Rubik
74
83
 
75
84
  # Condvar-parked, reap-immune; the resume_all targets.
76
85
  def parked?
77
- @monitor.synchronize { error_paused? || awaiting_budget? }
86
+ @monitor.synchronize { PARKED_STATES.include?(@state) }
78
87
  end
79
88
 
80
89
  # The no-resurrection set (kill's race window included).
@@ -0,0 +1,49 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rubik
4
+ module Orchestrator
5
+ module Subagent
6
+ # Pure pagination window arithmetic for subagent output streams
7
+ # (ResultArchive ≅ TranscriptReader — architecture scan 2026-11-06).
8
+ # Leaf helper: zero IO, zero locks, isolated and deterministic.
9
+ module Paging
10
+ Window = Struct.new(:cursor, :body, :next_cursor, :has_more, :total_chars, :returned_chars, keyword_init: true) do
11
+ def more? = has_more
12
+ alias_method :has_more?, :more?
13
+ end
14
+
15
+ module_function
16
+
17
+ # Clamps negative cursor values to 0.
18
+ def clamp_cursor(cursor)
19
+ [cursor.to_i, 0].max
20
+ end
21
+
22
+ # Computes the window slice for a given text and cursor/limit bounds.
23
+ # Returns nil if cursor exceeds total_chars.
24
+ def window(text, cursor:, limit:, default:, max:)
25
+ body = text.to_s
26
+ total = body.length
27
+ cur = clamp_cursor(cursor)
28
+ return nil if cur > total
29
+
30
+ size = limit.to_i
31
+ size = default if size <= 0
32
+ size = [size, max].min
33
+ slice = body[cur, size].to_s
34
+ nxt = cur + slice.length
35
+ has_more = nxt < total
36
+
37
+ Window.new(
38
+ cursor: cur,
39
+ body: slice,
40
+ next_cursor: has_more ? nxt : nil,
41
+ has_more: has_more,
42
+ total_chars: total,
43
+ returned_chars: slice.length
44
+ ).freeze
45
+ end
46
+ end
47
+ end
48
+ end
49
+ end
@@ -43,7 +43,7 @@ module Rubik
43
43
  next unless inst.archive!
44
44
 
45
45
  dropped_steering << id if inst.respond_to?(:pending_redeploy_messages?) && inst.pending_redeploy_messages?
46
- (@finished ||= {})[id] = inst
46
+ @finished[id] = inst
47
47
  reaped << id
48
48
  end
49
49
  reaped.each { |id| @instances.delete(id) }
@@ -85,8 +85,6 @@ module Rubik
85
85
  # FIFO taşma: en eski mezar taşı evict edilir ve cleanup ile
86
86
  # :disposed'a çekilir (ctx zaten dispose'lu; cleanup no-op güvenli).
87
87
  def evict_overflow!
88
- return unless @finished
89
-
90
88
  while @finished.size > tombstone_limit
91
89
  _id, inst = @finished.shift
92
90
  inst&.cleanup
@@ -0,0 +1,99 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rubik
4
+ module Orchestrator
5
+ module Subagent
6
+ # The redeploy entry's supervisor-plane support: refusal reasons, the
7
+ # root-coeffect preflight, the SS release hook, and the spawn-parity
8
+ # transaction rollback (rollback_spawn! family, spawn_transaction.rb).
9
+ # The irreversible step — redeploy_for!'s history append + inbox
10
+ # drain — is NOT reverted; rollback restores PLACEMENT atomicity only:
11
+ # unit registration, roster placement, the fresh child ctx. The
12
+ # instance stays terminal-and-settled; a retry re-appends one
13
+ # "[New task]" line — bounded, benign.
14
+ #
15
+ # from_finished note: reaping archives before tombstoning, and archived
16
+ # instances refuse redeploy — a tombstoned lookup serves only the refusal
17
+ # message. The restoration arm is drift defense for future reap semantics.
18
+ module RedeployTransaction
19
+ # SS bırakma kancası (spawn ile aynı düzen): başarılı redeploy'un
20
+ # SONRASINDAKİ süpürme hatası, zaten koşan transaction'ı fail
21
+ # etmesin — spawn'ın "release failed after successful spawn"
22
+ # warn-paritesi.
23
+ def release_ready_after_redeploy!
24
+ release_ready!
25
+ rescue StandardError => e
26
+ Rubik::Log.warn(:orchestrator,
27
+ "subagent dependency release failed after successful redeploy (#{e.class}: #{e.message})")
28
+ end
29
+
30
+ # Reddetme gerekçesi durum-bazlı yönlendirme içerir: maestro doğru
31
+ # aksiyona (steer / wait / taze spawn) yönelsin.
32
+ def redeploy_refusal(id, inst)
33
+ return "Subagent '#{id}' not found." unless inst
34
+ return "Subagent '#{id}' is archived (reaped) — spawn a fresh subagent via invoke_subagent." if inst.archived?
35
+
36
+ if inst.settled?
37
+ "Subagent '#{id}' is still settling (completion handling in flight); retry shortly."
38
+ else
39
+ "Subagent '#{id}' is #{inst.state} with a live thread — steer it (send_message / extend_budget) or kill it first."
40
+ end
41
+ end
42
+
43
+ # Spawn preflights this before any reservation (resolve_profile_snapshot);
44
+ # redeploy discovered the same failure only in activate_instance! —
45
+ # i.e. AFTER the irreversible instance mutation. Root coeffects are
46
+ # checked against the root context; activation's own provides
47
+ # (asker/sender/cancellation) are exempt.
48
+ def preflight_redeploy_coeffects!(profile, type_name:)
49
+ unless profile
50
+ raise ReservedProfileError,
51
+ "No subagent archetype is available for '#{type_name}' (removed from the registry since spawn?)."
52
+ end
53
+
54
+ missing = (profile.requires || []).reject do |name|
55
+ SpawnSupervisor::CHILD_CONTEXT_COEFFECTS.include?(name) ||
56
+ !Rubik::Coeffects.get(@root_context, name).nil?
57
+ end
58
+ raise UnsatisfiedCoeffectsError.new(profile.name, missing) unless missing.empty?
59
+ end
60
+
61
+ # pre_existing_unit: the unit owned by the PREVIOUS lifecycle (if any).
62
+ # Only a unit this transaction minted (identity differs) is unregistered
63
+ # — a pre-mint failure must not desync the kernel board by stripping
64
+ # the historical unit the supervisor never touched here.
65
+ def rollback_redeploy!(inst:, child_ctx:, from_finished:, init_supervisor:, pre_existing_unit:)
66
+ if inst.unit && !inst.unit.equal?(pre_existing_unit) && init_supervisor.respond_to?(:unregister)
67
+ begin
68
+ init_supervisor.unregister(inst.unit)
69
+ rescue StandardError => e
70
+ Rubik::Log.warn(:orchestrator,
71
+ "subagent redeploy unit rollback failed for '#{inst.id}' (#{e.class}: #{e.message})")
72
+ end
73
+ end
74
+
75
+ begin
76
+ inst.fail_turn!("redeploy activation failed: worker could not start") unless inst.settled? || inst.disposed?
77
+ rescue StandardError => e
78
+ Rubik::Log.warn(:orchestrator,
79
+ "subagent redeploy state rollback failed for '#{inst.id}' (#{e.class}: #{e.message})")
80
+ end
81
+
82
+ # Restore the tombstone the deletion removed. For an @instances
83
+ # origin the map moves were no-ops — deleting here would LOSE
84
+ # the instance instead of restoring placement.
85
+ @instances.delete(inst.id) if from_finished && @instances[inst.id].equal?(inst)
86
+ @finished[inst.id] = inst if from_finished
87
+
88
+ begin
89
+ child_ctx&.dispose
90
+ rescue StandardError => e
91
+ Rubik::Log.warn(:orchestrator,
92
+ "subagent redeploy context rollback failed for '#{inst.id}' (#{e.class}: #{e.message})")
93
+ end
94
+ nil
95
+ end
96
+ end
97
+ end
98
+ end
99
+ end
@@ -1,7 +1,9 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "monitor"
4
+ require_relative "paging"
4
5
  require_relative "../../security/redactor"
6
+ require_relative "../../storage/layout"
5
7
  require_relative "../../uris"
6
8
 
7
9
  module Rubik
@@ -139,20 +141,15 @@ module Rubik
139
141
  private
140
142
 
141
143
  def page_for(entry, cursor, limit)
142
- body = entry.body
143
- total = body.length
144
- cur = [cursor.to_i, 0].max
145
- return missing(entry.ref, :cursor, "Cursor #{cur} exceeds the retained result length (#{total} chars). Use cursor 0.") if cur > total
146
-
147
- size = limit.to_i
148
- size = @page_chars if size <= 0
149
- size = [size, MAX_PAGE_CHARS].min
150
- text = body[cur, size].to_s
151
- nxt = cur + text.length
152
- has_more = nxt < total
144
+ win = Paging.window(entry.body, cursor: cursor, limit: limit, default: @page_chars, max: MAX_PAGE_CHARS)
145
+ unless win
146
+ cur = Paging.clamp_cursor(cursor)
147
+ return missing(entry.ref, :cursor, "Cursor #{cur} exceeds the retained result length (#{entry.body.length} chars). Use cursor 0.")
148
+ end
149
+
153
150
  Page.new(ref: entry.ref, storage_id: entry.storage_id, id: entry.id, run: entry.run, state: entry.state,
154
- body: text, cursor: cur, next_cursor: has_more ? nxt : nil, total_chars: total,
155
- returned_chars: text.length, has_more: has_more, redacted: true,
151
+ body: win.body, cursor: win.cursor, next_cursor: win.next_cursor, total_chars: win.total_chars,
152
+ returned_chars: win.returned_chars, has_more: win.has_more, redacted: true,
156
153
  retained_at: entry.retained_at, expires_at: entry.expires_at)
157
154
  end
158
155
 
@@ -180,15 +177,8 @@ module Rubik
180
177
  end
181
178
  end
182
179
 
183
- def config_get(config, key, default)
184
- return default if config.nil?
185
-
186
- val = if config.is_a?(Hash)
187
- config[key] || config.dig(*key.split("."))
188
- elsif config.respond_to?(:fetch)
189
- config.fetch(key, nil)
190
- end
191
- val.nil? ? default : val
180
+ def config_get(config, key, default = nil)
181
+ Rubik::Storage::Layout.config_get(config, key, default)
192
182
  end
193
183
  end
194
184
  end