rubik 0.8.0 → 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 (47) hide show
  1. checksums.yaml +4 -4
  2. data/ATTRIBUTION.md +1 -1
  3. data/CHANGELOG.md +65 -1
  4. data/lib/rubik/kernel/dispatcher.rb +19 -23
  5. data/lib/rubik/kernel/init.rb +22 -18
  6. data/lib/rubik/orchestrator/goal_ledger/ledger.rb +3 -9
  7. data/lib/rubik/orchestrator/goal_ledger/observation_projection.rb +3 -9
  8. data/lib/rubik/orchestrator/subagent/deferred_spec.rb +51 -2
  9. data/lib/rubik/orchestrator/subagent/dependency.rb +20 -20
  10. data/lib/rubik/orchestrator/subagent/execution_reads.rb +1 -1
  11. data/lib/rubik/orchestrator/subagent/journal.rb +3 -9
  12. data/lib/rubik/orchestrator/subagent/lifecycle.rb +10 -1
  13. data/lib/rubik/orchestrator/subagent/paging.rb +49 -0
  14. data/lib/rubik/orchestrator/subagent/reaper.rb +1 -3
  15. data/lib/rubik/orchestrator/subagent/redeploy_transaction.rb +99 -0
  16. data/lib/rubik/orchestrator/subagent/result_archive.rb +12 -22
  17. data/lib/rubik/orchestrator/subagent/reuse.rb +37 -31
  18. data/lib/rubik/orchestrator/subagent/spawn_transaction.rb +1 -1
  19. data/lib/rubik/orchestrator/subagent/supervisor.rb +6 -2
  20. data/lib/rubik/orchestrator/subagent/task_ownership.rb +2 -2
  21. data/lib/rubik/orchestrator/subagent/transcript_reader.rb +14 -13
  22. data/lib/rubik/repl/commands/subagents.rb +3 -2
  23. data/lib/rubik/repl/pruner/service.rb +4 -9
  24. data/lib/rubik/runtime/context.rb +6 -1
  25. data/lib/rubik/runtime/fiber.rb +17 -5
  26. data/lib/rubik/runtime/manager.rb +19 -12
  27. data/lib/rubik/storage/layout.rb +14 -3
  28. data/lib/rubik/tools/base.rb +31 -0
  29. data/lib/rubik/tools/builtins/dmesg.rb +1 -1
  30. data/lib/rubik/tools/builtins/exec.rb +1 -2
  31. data/lib/rubik/tools/builtins/files.rb +1 -1
  32. data/lib/rubik/tools/builtins/goal_ledger.rb +1 -1
  33. data/lib/rubik/tools/builtins/grep.rb +2 -2
  34. data/lib/rubik/tools/builtins/interactive.rb +1 -3
  35. data/lib/rubik/tools/builtins/lsp.rb +2 -2
  36. data/lib/rubik/tools/builtins/pruner.rb +1 -1
  37. data/lib/rubik/tools/builtins/runtime.rb +1 -1
  38. data/lib/rubik/tools/builtins/send_message.rb +14 -3
  39. data/lib/rubik/tools/builtins/skill.rb +1 -1
  40. data/lib/rubik/tools/builtins/storage.rb +1 -1
  41. data/lib/rubik/tools/builtins/subagent.rb +2 -1
  42. data/lib/rubik/tools/builtins/subagent_lifecycle.rb +5 -3
  43. data/lib/rubik/tools/builtins/symbols.rb +4 -4
  44. data/lib/rubik/tools/builtins/task.rb +1 -1
  45. data/lib/rubik/tools/builtins/vakanuvis.rb +1 -1
  46. data/lib/rubik/version.rb +1 -1
  47. metadata +3 -1
@@ -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
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "reaper"
4
+ require_relative "redeploy_transaction"
4
5
 
5
6
  module Rubik
6
7
  module Orchestrator
@@ -88,6 +89,8 @@ module Rubik
88
89
  # imkânsız — bkz. activation.rb). provider/buffer/provider_gate/
89
90
  # storage_id/kimlik AYNEN KALIR (reuse'un kendisi bu).
90
91
  module RedeploySupervisor
92
+ include RedeployTransaction
93
+
91
94
  # `owner: :keep` (the default) keeps the instance's existing task
92
95
  # ownership; the tool plane passes the CURRENT turn's token so a
93
96
  # redeploy issued in this turn is cancellable with it (issue #125).
@@ -95,45 +98,48 @@ module Rubik
95
98
  prompt_str = prompt.to_s.strip
96
99
  raise ArgumentError, "Redeploy prompt cannot be empty" if prompt_str.empty?
97
100
 
101
+ lost_race = false # method scope: the block decides it, the tail reads it
98
102
  redeployed = @monitor.synchronize do
99
103
  key = id.to_s
100
- inst = @instances[key] || (@finished || {})[key]
104
+ inst = @instances[key] || @finished[key]
101
105
  raise ArgumentError, redeploy_refusal(key, inst) unless inst&.redeployable?
102
106
 
103
107
  eff_owner = owner == :keep ? inst.owner_task : owner
104
108
  refute_cancelled_owner!(eff_owner)
105
109
  validate_concurrency!
106
- child_ctx = extend_root_context!(:redeploy)
107
- profile = inst.profile_snapshot || @type_registry.get(inst.type_name)
108
- scoped_registry = build_scoped_registry(profile, child_ctx, inst.buffer_manager)
109
- return false unless inst.redeploy_for!(prompt: prompt_str, max_steps: (max_steps || @default_max_steps).to_i,
110
- context: child_ctx, tool_registry: scoped_registry,
111
- owner_task: eff_owner)
112
-
113
- @finished&.delete(inst.id)
114
- @instances[inst.id] = inst
115
- activate_instance!(inst, child_ctx: child_ctx, owner_token: eff_owner)
116
- end
117
- # Start-to-Start (SS) bırakma kancası: redeploy da bir başlangıçtır — taze :running
118
- # flip'i, bu id'yi Start-to-Start (SS) ile bekleyen kuyruk spesifikasyonlarını
119
- # bırakır (kilit DIŞINDA — emit kuralı; spawn ile aynı düzen).
120
- release_ready!
121
- redeployed
122
- end
123
-
124
- private
125
-
126
- # Reddetme gerekçesi durum-bazlı yönlendirme içerir: maestro doğru
127
- # aksiyona (steer / wait / taze spawn) yönelsin.
128
- def redeploy_refusal(id, inst)
129
- return "Subagent '#{id}' not found." unless inst
130
- return "Subagent '#{id}' is archived (reaped) — spawn a fresh subagent via invoke_subagent." if inst.archived?
131
-
132
- if inst.settled?
133
- "Subagent '#{id}' is still settling (completion handling in flight); retry shortly."
134
- else
135
- "Subagent '#{id}' is #{inst.state} with a live thread — steer it (send_message / extend_budget) or kill it first."
110
+ child_ctx = nil
111
+ pre_existing_unit = inst.unit
112
+ from_finished = @finished.key?(key)
113
+ eff_init = init_for_activation
114
+ begin
115
+ child_ctx = extend_root_context!(:redeploy)
116
+ profile = inst.profile_snapshot || @type_registry.get(inst.type_name)
117
+ preflight_redeploy_coeffects!(profile, type_name: inst.type_name)
118
+ scoped_registry = build_scoped_registry(profile, child_ctx, inst.buffer_manager)
119
+ lost_race = !inst.redeploy_for!(prompt: prompt_str, max_steps: (max_steps || @default_max_steps).to_i,
120
+ context: child_ctx, tool_registry: scoped_registry,
121
+ owner_task: eff_owner)
122
+ if lost_race
123
+ # Settle race (reaper archived / kill landed between the checks):
124
+ # the fresh child ctx was never bound into a worker — dispose it
125
+ # instead of leaking it into the parent accumulator.
126
+ child_ctx&.dispose
127
+ else
128
+ @finished.delete(inst.id)
129
+ @instances[inst.id] = inst
130
+ activate_instance!(inst, child_ctx: child_ctx, owner_token: eff_owner,
131
+ init_supervisor: eff_init)
132
+ end
133
+ rescue StandardError
134
+ rollback_redeploy!(inst: inst, child_ctx: child_ctx, from_finished: from_finished,
135
+ init_supervisor: eff_init, pre_existing_unit: pre_existing_unit)
136
+ raise
137
+ end
138
+ inst unless lost_race
136
139
  end
140
+ # SS bırakma kancası lost race'te atlanır: orijinal erken-return semantiği.
141
+ release_ready_after_redeploy! unless lost_race
142
+ lost_race ? false : redeployed
137
143
  end
138
144
  end
139
145
  end
@@ -99,7 +99,7 @@ module Rubik
99
99
  # next sequence number here and return it if activation rolls back.
100
100
  generated_id = reserved_id.nil?
101
101
  subagent_id = generated_id ? "subagent-#{@counter + 1}" : reserved_id.to_s
102
- id_in_use = @instances.key?(subagent_id) || (@finished || {}).key?(subagent_id)
102
+ id_in_use = @instances.key?(subagent_id) || @finished.key?(subagent_id)
103
103
  raise ArgumentError, "Subagent id '#{subagent_id}' is already in use." if id_in_use
104
104
 
105
105
  @counter += 1 if generated_id
@@ -66,6 +66,10 @@ module Rubik
66
66
 
67
67
  @type_registry = TypeRegistry.new(default_context: @root_context)
68
68
  @instances = {}
69
+ # Tombstone table (reaped executions) is born here beside its
70
+ # sibling maps — ReaperSupervisor writes it, every reader may
71
+ # assume it is initialized.
72
+ @finished = {}
69
73
  @deferred = {}
70
74
  @monitor = Monitor.new
71
75
  @wait_cond = @monitor.new_cond
@@ -95,7 +99,7 @@ module Rubik
95
99
  @root_context.register_disposable { shutdown_all } if @root_context.respond_to?(:register_disposable)
96
100
  end
97
101
 
98
- def get(id) = @monitor.synchronize { @instances[id.to_s] || (@finished ||= {})[id.to_s] || queued_spec(id.to_s) }
102
+ def get(id) = @monitor.synchronize { @instances[id.to_s] || @finished[id.to_s] || queued_spec(id.to_s) }
99
103
 
100
104
  def extend_budget(id, steps = Budget::DEFAULT_GRANT_STEPS)
101
105
  inst = get(id)
@@ -125,7 +129,7 @@ module Rubik
125
129
 
126
130
  def list(parent_id: nil)
127
131
  @monitor.synchronize do
128
- items = @instances.values + (@finished ||= {}).values + @deferred.values
132
+ items = @instances.values + @finished.values + @deferred.values
129
133
  items = items.select { |i| i.parent_id == parent_id.to_s } if parent_id
130
134
  items.sort_by { |i| i.started_at || Time.at(0) }
131
135
  end
@@ -51,7 +51,7 @@ module Rubik
51
51
  end
52
52
 
53
53
  remaining = @monitor.synchronize do
54
- (@instances.values + (@finished || {}).values + requested.values).uniq.select do |inst|
54
+ (@instances.values + @finished.values + requested.values).uniq.select do |inst|
55
55
  owned_by?(inst, token) && !cancellation_settled?(inst)
56
56
  end
57
57
  end
@@ -97,7 +97,7 @@ module Rubik
97
97
  def cancel_queued_specs(token)
98
98
  queued = @monitor.synchronize do
99
99
  specs = @deferred.values.select { |spec| spec.respond_to?(:owner) && spec.owner.equal?(token) }
100
- specs.each { |spec| cancel_spec!(spec, "owner task cancelled (^C)") }
100
+ specs.each { |spec| spec.cancel!("owner task cancelled (^C)") }
101
101
  specs
102
102
  end
103
103
  announce_cancellations(queued)
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "digest"
4
+ require_relative "paging"
4
5
  require_relative "transcript_formatter"
5
6
  require_relative "../../uris"
6
7
 
@@ -21,8 +22,12 @@ module Rubik
21
22
  # execution state, and never touch the workspace gate: live comes from
22
23
  # the instance roster, disk from the execution's own storage-id path.
23
24
  module TranscriptReader
24
- # A live execution whose memory snapshot is the freshest source.
25
- ACTIVE_STATES = ["pending", "running", "waiting_input", "waiting_budget", "paused_error", "canceling", "queued"].freeze
25
+ # A live execution whose memory snapshot is the freshest source. The
26
+ # instance vocabulary only — "queued" was dead data here: an Instance
27
+ # can never hold :queued (TRANSITIONS has no such state), and the
28
+ # tool plane resolves queued specs to their own handling before
29
+ # read_transcript is ever reached.
30
+ ACTIVE_STATES = ["pending", "running", "waiting_input", "waiting_budget", "paused_error", "canceling"].freeze
26
31
 
27
32
  # Page size stays under the tool-output truncation ceiling (head_tail
28
33
  # would otherwise eat the middle of a page); the hard cap bounds a
@@ -135,20 +140,16 @@ module Rubik
135
140
  "Start a new read at cursor 0 to get a consistent snapshot.")
136
141
  end
137
142
 
138
- total = text.length
139
- cur = [cursor.to_i, 0].max
140
- return missing(sid, :cursor, "Cursor #{cur} exceeds the transcript length (#{total} chars). Use cursor 0.") if cur > total
143
+ win = Paging.window(text, cursor: cursor, limit: limit, default: DEFAULT_PAGE_CHARS, max: MAX_PAGE_CHARS)
144
+ unless win
145
+ cur = Paging.clamp_cursor(cursor)
146
+ return missing(sid, :cursor, "Cursor #{cur} exceeds the transcript length (#{text.length} chars). Use cursor 0.")
147
+ end
141
148
 
142
- size = limit.to_i
143
- size = DEFAULT_PAGE_CHARS if size <= 0
144
- size = [size, MAX_PAGE_CHARS].min
145
- body = text[cur, size].to_s
146
- nxt = cur + body.length
147
- has_more = nxt < total
148
149
  Page.new(storage_id: sid, id: instance&.id, source: source, snapshot: token,
149
150
  state: instance.respond_to?(:state) ? instance.state&.to_s : nil, persisted: source == "disk",
150
- body: body, cursor: cur, next_cursor: has_more ? nxt : nil, total_chars: total,
151
- returned_chars: body.length, has_more: has_more)
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)
152
153
  end
153
154
 
154
155
  def missing(storage_id, reason, message)
@@ -63,10 +63,11 @@ module Rubik
63
63
 
64
64
  ctx.out.puts "=== Subagent Process Hierarchy (#{instances.size} tracked, #{sup.active_count} active) ==="
65
65
  instances.each do |inst|
66
+ # A :spawning spec is mid-launch, not ended — ask spec vocabulary directly.
66
67
  dur = if inst.running?
67
68
  "up #{inst.uptime.round(1)}s"
68
- elsif inst.state == :queued
69
- "queued (waiting on: #{inst.depends_on.join(', ')})"
69
+ elsif inst.respond_to?(:spawning?) && (inst.queued? || inst.spawning?)
70
+ "queued/launching (waiting on: #{inst.depends_on.join(', ')})"
70
71
  else
71
72
  "ended (#{inst.uptime.round(1)}s)"
72
73
  end
@@ -1,5 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "../../storage/layout"
4
+
3
5
  module Rubik
4
6
  module REPL
5
7
  module Pruner
@@ -66,15 +68,8 @@ module Rubik
66
68
  # Noktalı anahtar okuması iki config şeklinde de aynı çalışsın
67
69
  # (maestro_gate.rb:38-40 düzeni): Rubik::Config#fetch noktalı yolu
68
70
  # böler, düz Hash hepsini tek anahtar sayar → dig'e düş.
69
- def config_get(config, key, default)
70
- return default if config.nil?
71
-
72
- val = if config.is_a?(Hash)
73
- config.dig(*key.to_s.split("."))
74
- elsif config.respond_to?(:fetch)
75
- config.fetch(key, nil)
76
- end
77
- val.nil? ? default : val
71
+ def config_get(config, key, default = nil)
72
+ Rubik::Storage::Layout.config_get(config, key, default)
78
73
  end
79
74
  end
80
75
  end
@@ -74,6 +74,8 @@ module Rubik
74
74
  def provide(name, service)
75
75
  key = name.to_s.downcase
76
76
  @monitor.synchronize do
77
+ raise ContextDisposedError, "Cannot provide '#{name}' on a disposed context." if @disposed
78
+
77
79
  already_provided = @services.key?(key)
78
80
  @services[key] = service
79
81
  return if already_provided
@@ -219,6 +221,10 @@ module Rubik
219
221
  protected :prune_child
220
222
 
221
223
  def dispose
224
+ return if disposed?
225
+
226
+ # Resolve dmesg outside monitor to preserve parent→child lock order (F3).
227
+ dmesg = resolve_dmesg
222
228
  parent = nil
223
229
  deferred_interrupt = nil
224
230
  @monitor.synchronize do
@@ -230,7 +236,6 @@ module Rubik
230
236
  # (record_deferred_signal) survive into the final
231
237
  # last_dispose_errors instead of being wiped by this reset.
232
238
  @last_dispose_errors = []
233
- dmesg = resolve_dmesg
234
239
  # Counted before the cascade: disposing children prune their
235
240
  # inverses from our accumulator (pre-cascade size is what the
236
241
  # "beginning" log reports).
@@ -90,12 +90,13 @@ module Rubik
90
90
  true
91
91
  rescue StandardError => e
92
92
  # Atomic Rollback on Error: unwind partial inverses immediately
93
- @sub_context&.dispose
94
- @sub_context = nil
95
- @instance = nil
96
- @state = :failed
97
- @last_error = e
93
+ rollback_activation!(e)
98
94
  false
95
+ rescue Exception => e # rubocop:disable Lint/RescueException
96
+ # Failure Reversibility on fatal exceptions/signals (Interrupt, SystemExit):
97
+ # execute partial inverses immediately to restore the environment, then re-raise (AGENTS.md §1.A).
98
+ rollback_activation!(e)
99
+ raise
99
100
  end
100
101
  end
101
102
 
@@ -130,6 +131,17 @@ module Rubik
130
131
  def build_instance(_sub_context, _config)
131
132
  nil
132
133
  end
134
+
135
+ private
136
+
137
+ def rollback_activation!(error)
138
+ ctx = @sub_context
139
+ @sub_context = nil
140
+ @instance = nil
141
+ @state = :failed
142
+ @last_error = error
143
+ ctx&.dispose
144
+ end
133
145
  end
134
146
 
135
147
  # Backwards-compatibility alias (AGENTS.md terminology). Kept for external
@@ -101,7 +101,11 @@ module Rubik
101
101
  # object is re-provided (identity change), so its new instance is injected.
102
102
  # Both transitions run reconcile_all(changed_service:) OUTSIDE the monitor.
103
103
  def provide(service_name, service)
104
- @monitor.synchronize { @context.provide(service_name, service) }
104
+ @monitor.synchronize do
105
+ raise ContextDisposedError, "Cannot provide service on a disposed Manager" if @disposed
106
+
107
+ @context.provide(service_name, service)
108
+ end
105
109
  # reconcile_all runs OUTSIDE this lock so a failing fiber's backoff sleep
106
110
  # never serializes other threads (Finding 3).
107
111
  reconcile_all(changed_service: service_name)
@@ -198,22 +202,25 @@ module Rubik
198
202
  end
199
203
 
200
204
  def dispose!
205
+ fibers_to_dispose = nil
201
206
  @monitor.synchronize do
202
207
  return if @disposed
203
208
 
204
209
  @disposed = true
205
- begin
206
- @fibers.values.reverse_each do |fiber|
207
- fiber.dispose!
208
- rescue StandardError => e
209
- Rubik::Log.warn(:runtime, "fiber '#{fiber.name}' dispose failed: #{e.class}: #{e.message}")
210
- end
211
- ensure
212
- @fibers.clear
213
- @retry_gate.clear_all # fresh-eye R2: no bookkeeping outlives the manager
214
- @context.dispose
215
- end
210
+ fibers_to_dispose = @fibers.values.reverse
211
+ @fibers.clear
212
+ @retry_gate.clear_all # fresh-eye R2: no bookkeeping outlives the manager
213
+ end
214
+
215
+ # Execute fiber teardown and context disposal OUTSIDE the monitor lock
216
+ # so arbitrary user teardown inverses never serialize manager operations (Finding F4).
217
+ fibers_to_dispose.each do |fiber|
218
+ fiber.dispose!
219
+ rescue StandardError => e
220
+ Rubik::Log.warn(:runtime, "fiber '#{fiber.name}' dispose failed: #{e.class}: #{e.message}")
216
221
  end
222
+
223
+ @context.dispose
217
224
  end
218
225
 
219
226
  private
@@ -16,13 +16,24 @@ module Rubik
16
16
  DEFAULT_ROOT = "~/.rubik/rubikstorage"
17
17
 
18
18
  # Noktalı anahtar okuması her iki config şeklinde aynı çalışsın:
19
- # Rubik::Config#fetch noktalı yolları böler, düz Hash#fetch BÜTÜN
20
- # dizgiyi tek anahtar sayar — Hash için dig, diğerleri için fetch.
19
+ # Rubik::Config#fetch noktalı yolları böler, düz Hash için hem düz
20
+ # anahtar (config[key]) hem de iç içe Hash (dig) desteklenir —
21
+ # Hash için flat || dig, diğerleri için fetch, nil durumunda default.
21
22
  def config_get(config, key, default = nil)
22
23
  return default if config.nil?
23
24
 
24
25
  val = if config.is_a?(Hash)
25
- config.dig(*key.to_s.split("."))
26
+ if config.key?(key)
27
+ config[key]
28
+ elsif config.key?(key.to_s)
29
+ config[key.to_s]
30
+ else
31
+ begin
32
+ config.dig(*key.to_s.split("."))
33
+ rescue TypeError
34
+ nil
35
+ end
36
+ end
26
37
  elsif config.respond_to?(:fetch)
27
38
  config.fetch(key, nil)
28
39
  end
@@ -2,6 +2,8 @@
2
2
 
3
3
  require "pathname"
4
4
  require_relative "declaration"
5
+ require_relative "services" unless defined?(Rubik::Tools::Services)
6
+ require_relative "../coeffects" unless defined?(Rubik::Coeffects)
5
7
 
6
8
  module Rubik
7
9
  module Tools
@@ -76,6 +78,35 @@ module Rubik
76
78
  end
77
79
  end
78
80
 
81
+ # Single home for tool-side coeffect and service resolution (architecture
82
+ # review Candidate A2, issue #368). Unifies the 3 scattered tool-side
83
+ # dialects:
84
+ # 1. Coeffects.resolve(@runtime_context, KEY, @fallback)
85
+ # 2. @fallback || (ctx.respond_to?(:get) ? Coeffects.get(...) : nil)
86
+ # 3. @runtime_manager.context coeffect lookups
87
+ #
88
+ # Delegates directly to Tools::Services::COEFFECTS and Coeffects.get so
89
+ # no third resolution home is created. If the runtime context does not
90
+ # satisfy the coeffect, falls back to the explicitly passed `fallback`,
91
+ # or to an instance variable matching `@#{key}` if defined.
92
+ #
93
+ # task_mgr = service(:task_manager)
94
+ # harness = service(:pruner, @harness)
95
+ # asker = service(:subagent_question_asker)
96
+ def service(key, fallback = nil, ctx: nil)
97
+ effective_ctx = ctx || (defined?(@runtime_context) ? @runtime_context : nil)
98
+ effective_ctx ||= (@runtime_manager.context if defined?(@runtime_manager) && @runtime_manager.respond_to?(:context))
99
+
100
+ coeffect_key = Rubik::Tools::Services::COEFFECTS[key] || Rubik::Coeffects.canonical(key)
101
+ resolved = Rubik::Coeffects.get(effective_ctx, coeffect_key) if effective_ctx
102
+ return resolved unless nil.equal?(resolved)
103
+
104
+ return fallback unless nil.equal?(fallback)
105
+
106
+ ivar = :"@#{key}"
107
+ instance_variable_defined?(ivar) ? instance_variable_get(ivar) : nil
108
+ end
109
+
79
110
  # Normalizes a model-supplied path filter against the tool's root
80
111
  # directory: backslashes become slashes, "./" is stripped, and ABSOLUTE
81
112
  # paths (C:/…, /…) are relativized when they sit inside the root.
@@ -67,7 +67,7 @@ module Rubik
67
67
  private
68
68
 
69
69
  def resolve_dmesg
70
- @dmesg || (@runtime_context.respond_to?(:get) ? Rubik::Coeffects.get(@runtime_context, Rubik::Coeffects::DMESG) : nil)
70
+ service(:dmesg)
71
71
  end
72
72
  end
73
73
  end
@@ -187,8 +187,7 @@ module Rubik
187
187
  private
188
188
 
189
189
  def execute_background(cmd)
190
- task_mgr = @task_manager ||
191
- (@runtime_context.respond_to?(:get) ? Rubik::Coeffects.get(@runtime_context, Rubik::Coeffects::TASK_MANAGER) : nil)
190
+ task_mgr = service(:task_manager)
192
191
  if task_mgr.nil?
193
192
  return Rubik::Tools::Result.new(tool_name: "run_command", status: :error,
194
193
  output: "TaskManager is not available to run commands in background.",
@@ -166,7 +166,7 @@ module Rubik
166
166
  end
167
167
 
168
168
  def context_index
169
- Rubik::Coeffects.resolve(@runtime_context, Rubik::Coeffects::CONTEXT_INDEX, @context_index)
169
+ service(:context_index, @context_index)
170
170
  end
171
171
 
172
172
  def execute(args = {})
@@ -53,7 +53,7 @@ module Rubik
53
53
  "{\"rev\": N, \"ops\": [...]}.")
54
54
  end
55
55
 
56
- ledger = Rubik::Coeffects.resolve(@runtime_context, Rubik::Coeffects::GOAL_LEDGER, nil)
56
+ ledger = service(:goal_ledger)
57
57
  unless ledger
58
58
  return ToolOutput.error("Goal ledger is not available: no running !goal loop (or goal.ledger.enabled=false). " \
59
59
  "The ledger exists only while a goal loop runs; update it after each meaningful step.")
@@ -45,11 +45,11 @@ module Rubik
45
45
  end
46
46
 
47
47
  def context_index
48
- Rubik::Coeffects.resolve(@runtime_context, Rubik::Coeffects::CONTEXT_INDEX, @context_index)
48
+ service(:context_index, @context_index)
49
49
  end
50
50
 
51
51
  def buffer_manager
52
- Rubik::Coeffects.resolve(@runtime_context, Rubik::Coeffects::BUFFER_MANAGER, @buffer_manager)
52
+ service(:buffer_manager, @buffer_manager)
53
53
  end
54
54
 
55
55
  def execute(args = {})