rubik 0.7.1 → 0.8.0

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 (46) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +141 -1
  3. data/lib/rubik/ast/typescript_extractor.rb +2 -2
  4. data/lib/rubik/config/deep_ops.rb +14 -0
  5. data/lib/rubik/config/defaults.rb +5 -4
  6. data/lib/rubik/config/env_loader.rb +88 -0
  7. data/lib/rubik/config/model_catalog.rb +13 -0
  8. data/lib/rubik/config/pruner.rb +34 -0
  9. data/lib/rubik/config/schema.rb +163 -0
  10. data/lib/rubik/config/scoped.rb +108 -0
  11. data/lib/rubik/config/store.rb +19 -8
  12. data/lib/rubik/config.rb +129 -53
  13. data/lib/rubik/diagnostics/parser.rb +2 -2
  14. data/lib/rubik/orchestrator/step_executor.rb +12 -59
  15. data/lib/rubik/orchestrator/subagent/scoped_registry.rb +14 -23
  16. data/lib/rubik/orchestrator/subagent/spawn_transaction.rb +12 -2
  17. data/lib/rubik/orchestrator/subagent/tool_dispatch.rb +12 -49
  18. data/lib/rubik/orchestrator/turn_executor.rb +9 -4
  19. data/lib/rubik/repl/commands/workspace.rb +14 -8
  20. data/lib/rubik/repl/lifecycle.rb +11 -0
  21. data/lib/rubik/repl/service_catalog.rb +2 -1
  22. data/lib/rubik/sandbox/runner.rb +28 -13
  23. data/lib/rubik/storage/render.rb +1 -1
  24. data/lib/rubik/storage/vakanuvis/distill_gate.rb +3 -3
  25. data/lib/rubik/storage/vakanuvis/harness.rb +4 -65
  26. data/lib/rubik/storage/vakanuvis/orientation.rb +1 -2
  27. data/lib/rubik/storage/vakanuvis/recall.rb +84 -0
  28. data/lib/rubik/storage/vakanuvis.rb +1 -0
  29. data/lib/rubik/tools/base.rb +34 -0
  30. data/lib/rubik/tools/builtins/define_subagent.rb +6 -0
  31. data/lib/rubik/tools/builtins/dmesg.rb +4 -4
  32. data/lib/rubik/tools/builtins/files.rb +18 -24
  33. data/lib/rubik/tools/builtins/goal_ledger.rb +1 -1
  34. data/lib/rubik/tools/builtins/grep.rb +6 -6
  35. data/lib/rubik/tools/builtins/interactive.rb +6 -0
  36. data/lib/rubik/tools/builtins/lifecycle.rb +2 -1
  37. data/lib/rubik/tools/builtins/pruner.rb +1 -1
  38. data/lib/rubik/tools/builtins/send_message.rb +6 -0
  39. data/lib/rubik/tools/builtins/subagent.rb +12 -0
  40. data/lib/rubik/tools/builtins/vakanuvis.rb +1 -1
  41. data/lib/rubik/tools/catalog.rb +19 -0
  42. data/lib/rubik/tools/declaration.rb +15 -2
  43. data/lib/rubik/tools/result_normalizer.rb +115 -0
  44. data/lib/rubik/tools/truncator.rb +3 -3
  45. data/lib/rubik/version.rb +1 -1
  46. metadata +7 -1
@@ -3,6 +3,7 @@
3
3
  require "yaml"
4
4
  require "yaml/store"
5
5
  require "fileutils"
6
+ require_relative "pruner"
6
7
 
7
8
  module Rubik
8
9
  class Config
@@ -71,16 +72,17 @@ module Rubik
71
72
  store.transaction do
72
73
  # Read existing data on disk
73
74
  existing = store.roots.to_h { |k| [k, store[k]] }
74
- merged = deep_merge(existing, deep_stringify_keys(@data))
75
+ scope_data = (scope_sym == :project ? @project_layer : @global_layer) || {}
76
+ merged = deep_merge(existing, deep_stringify_keys(scope_data))
75
77
 
76
78
  # Explicitly overwrite model and role specs so stale keys from prior providers are not retained
77
- if @data["models"].is_a?(Hash)
79
+ if scope_data["models"].is_a?(Hash)
78
80
  merged["models"] ||= {}
79
- @data["models"].each do |r_name, r_spec|
81
+ scope_data["models"].each do |r_name, r_spec|
80
82
  merged["models"][r_name.to_s] = deep_dup(r_spec)
81
83
  end
82
84
  end
83
- merged["model"] = deep_dup(@data["model"]) if @data["model"].is_a?(Hash)
85
+ merged["model"] = deep_dup(scope_data["model"]) if scope_data["model"].is_a?(Hash)
84
86
 
85
87
  # Replay nested deletions so validate_schema sees what will be written.
86
88
  # A blocked path means the deletion cannot reach disk and would
@@ -89,11 +91,14 @@ module Rubik
89
91
  unapplied = Array(deletions).select { |path| deep_delete(merged, path) == :blocked }
90
92
  validation_error = "could not apply deletion(s): #{unapplied.join(', ')}" if unapplied.any?
91
93
 
94
+ # Prune redundant defaults against DEFAULT_CONFIG on save
95
+ pruned = Pruner.prune(merged, DEFAULT_CONFIG)
96
+
92
97
  # Schema validation
93
98
  unless validation_error
94
99
  begin
95
100
  validate_schema(@data)
96
- validate_schema(merged)
101
+ validate_schema(pruned)
97
102
  rescue ArgumentError => e
98
103
  validation_error = e.message
99
104
  end
@@ -101,10 +106,16 @@ module Rubik
101
106
  store.abort if validation_error
102
107
 
103
108
  # Remove deleted roots
104
- (store.roots - merged.keys).each { |r| store.delete(r) }
109
+ (store.roots - pruned.keys).each { |r| store.delete(r) }
110
+
111
+ # Save pruned entries
112
+ pruned.each { |k, v| store[k] = v }
105
113
 
106
- # Save merged entries
107
- merged.each { |k, v| store[k] = v }
114
+ if scope_sym == :project
115
+ @project_layer = deep_dup(pruned)
116
+ else
117
+ @global_layer = deep_dup(pruned)
118
+ end
108
119
  end
109
120
 
110
121
  if validation_error
data/lib/rubik/config.rb CHANGED
@@ -1,9 +1,14 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "monitor"
3
4
  require_relative "config/defaults"
4
5
  require_relative "config/deep_ops"
5
6
  require_relative "config/store"
6
7
  require_relative "config/model_catalog"
8
+ require_relative "config/pruner"
9
+ require_relative "config/schema"
10
+ require_relative "config/env_loader"
11
+ require_relative "config/scoped"
7
12
 
8
13
  module Rubik
9
14
  class Config
@@ -14,25 +19,24 @@ module Rubik
14
19
 
15
20
  DEFAULT_CONFIG = Defaults::DEFAULT_CONFIG
16
21
 
17
- attr_reader :data, :warnings, :root_dir, :home_dir
22
+ attr_reader :data, :warnings, :root_dir, :home_dir,
23
+ :defaults_layer, :global_layer, :project_layer, :env_layer, :session_layer
18
24
  attr_accessor :event_bus
19
25
 
20
26
  def initialize(root_dir: Dir.pwd, home_dir: nil)
27
+ @monitor = Monitor.new
21
28
  @root_dir = File.expand_path(root_dir)
22
- effective_home = home_dir || (if Rubik.const_defined?(:Platform)
23
- Rubik::Platform.home_dir
24
- else
25
- begin
26
- Dir.home
27
- rescue ArgumentError
28
- (ENV["USERPROFILE"] || ENV["HOME"] || ".")
29
- end
30
- end)
29
+ effective_home = home_dir || (Rubik.const_defined?(:Platform) ? Rubik::Platform.home_dir : (ENV["USERPROFILE"] || ENV["HOME"] || "."))
31
30
  @home_dir = File.expand_path(effective_home)
32
31
  @warnings = []
33
32
  @stores = {}
34
33
  @listeners = []
35
34
  @event_bus = nil
35
+ @session_layer = {}
36
+ @defaults_layer = deep_dup(DEFAULT_CONFIG)
37
+ @global_layer = {}
38
+ @project_layer = {}
39
+ @env_layer = {}
36
40
  ensure_rubik_directories
37
41
  @data = load_merged_config
38
42
  end
@@ -40,19 +44,25 @@ module Rubik
40
44
  def on_change(prefix = nil, &block)
41
45
  return proc {} unless block_given?
42
46
 
43
- norm_prefix = prefix&.to_s&.sub(/\.\z/, "")
44
- entry = { prefix: norm_prefix, callback: block }
45
- @listeners << entry
46
- proc { @listeners.delete(entry) }
47
+ @monitor.synchronize do
48
+ norm_prefix = prefix&.to_s&.sub(/\.\z/, "")
49
+ entry = { prefix: norm_prefix, callback: block }
50
+ @listeners << entry
51
+ proc do
52
+ @monitor.synchronize { @listeners.delete(entry) }
53
+ end
54
+ end
47
55
  end
48
56
 
49
57
  # Retrieves a configuration value by dot-separated key path.
50
58
  def fetch(key, default = nil)
51
- keys = key.to_s.split(".")
52
- keys.reduce(@data) do |acc, k|
53
- return default unless acc.is_a?(Hash) && acc.key?(k)
59
+ @monitor.synchronize do
60
+ keys = key.to_s.split(".")
61
+ keys.reduce(@data) do |acc, k|
62
+ return default unless acc.is_a?(Hash) && acc.key?(k)
54
63
 
55
- acc[k]
64
+ acc[k]
65
+ end
56
66
  end
57
67
  end
58
68
 
@@ -66,35 +76,92 @@ module Rubik
66
76
  # {ok: false, error:, reason: :persist_failed} when the write failed —
67
77
  # so callers report honestly instead of assuming success.
68
78
  def set(key, value, persist: nil)
69
- old_val = fetch(key)
70
- typed_val = parse_scalar_value(value)
71
- validate_prompt_grace_value!(key.to_s, typed_val)
72
- validate_schema(typed_val, DEFAULT_CONFIG["ui"], "ui") if key.to_s == "ui" && typed_val.is_a?(Hash)
73
- keys = key.to_s.split(".")
74
- last_key = keys.pop
75
- target = keys.reduce(@data) do |acc, k|
76
- acc[k] ||= {}
77
- acc[k]
79
+ @monitor.synchronize do
80
+ old_val = fetch(key)
81
+ typed_val = parse_scalar_value(value)
82
+ typed_val = Schema.coerce(key, typed_val)
83
+ Schema.validate_value!(key, typed_val, strict: true)
84
+ if typed_val.is_a?(Hash)
85
+ typed_val = deep_dup(typed_val)
86
+ Schema.coerce_nested!(typed_val, key.to_s)
87
+ # Only spec'd sections validate their leaves — open sections
88
+ # (providers, adapter) accept arbitrary child keys silently.
89
+ section = DEFAULT_CONFIG[key.to_s]
90
+ validate_schema(typed_val, section, key.to_s) if section.is_a?(Hash) && !section.empty?
91
+ end
92
+
93
+ deep_set_key(@data, key, typed_val)
94
+
95
+ if persisting?(persist)
96
+ scope_sym = persist.to_s.downcase.to_sym == :project ? :project : :global
97
+ layer = scope_sym == :project ? (@project_layer ||= {}) : (@global_layer ||= {})
98
+ deep_set_key(layer, key, typed_val)
99
+ else
100
+ @session_layer ||= {}
101
+ deep_set_key(@session_layer, key, typed_val)
102
+ end
103
+
104
+ res = persisting?(persist) ? persist_result(save!(persist)) : { ok: true }
105
+ res[:reason] = :persist_failed unless res[:ok]
106
+ notify_change(key, typed_val, old_val) if old_val != typed_val
107
+ res
78
108
  end
79
- target[last_key] = typed_val
109
+ end
80
110
 
81
- res = persisting?(persist) ? persist_result(save!(persist)) : { ok: true }
82
- res[:reason] = :persist_failed unless res[:ok]
83
- notify_change(key, typed_val, old_val) if old_val != typed_val
84
- res
111
+ # Sets a temporary configuration change within a Context lifecycle (AGENTS.md Ω).
112
+ # When ctx is disposed, the inverse restores the prior configuration value.
113
+ def set_revertible(ctx, key, new_val)
114
+ @monitor.synchronize do
115
+ old_val = fetch(key)
116
+ had_key = !old_val.nil?
117
+ set(key, new_val, persist: nil)
118
+ return unless ctx.respond_to?(:on_dispose)
119
+
120
+ ctx.on_dispose do
121
+ if had_key
122
+ set(key, old_val, persist: nil)
123
+ else
124
+ delete(key, persist: nil)
125
+ end
126
+ end
127
+ end
128
+ end
129
+
130
+ # Creates an isolated, scoped child configuration (AGENTS.md Unified Context).
131
+ # Reads fall back to parent; writes modify only the child; persistence is fail-closed.
132
+ def extend(overrides = {})
133
+ Scoped.new(self, overrides)
85
134
  end
86
135
 
87
136
  # Removes the dot-path key from configuration, persisting like set.
88
137
  # Deleting an absent key is a successful no-op. Returns the persist
89
- # outcome (see set); notifies no listener — deletion callers refresh
90
- # the runtime explicitly.
138
+ # outcome (see set); notifies listeners on change.
91
139
  def delete(key, persist: nil)
92
- blocked = deep_delete(@data, key) == :blocked
93
- return { ok: false, error: "cannot delete '#{key}': path traverses a non-hash value" } if blocked
140
+ @monitor.synchronize do
141
+ old_val = fetch(key)
142
+ blocked = deep_delete(@data, key) == :blocked
143
+ return { ok: false, error: "cannot delete '#{key}': path traverses a non-hash value" } if blocked
144
+
145
+ if persisting?(persist)
146
+ scope_sym = persist.to_s.downcase.to_sym == :project ? :project : :global
147
+ layer = scope_sym == :project ? @project_layer : @global_layer
148
+ deep_delete(layer, key) if layer.is_a?(Hash)
149
+ elsif @session_layer.is_a?(Hash)
150
+ deep_delete(@session_layer, key)
151
+ end
152
+
153
+ recompute_data!
154
+
155
+ res = persisting?(persist) ? persist_result(save!(persist, deletions: [key])) : { ok: true }
156
+ res[:reason] = :persist_failed unless res[:ok]
94
157
 
95
- res = persisting?(persist) ? persist_result(save!(persist, deletions: [key])) : { ok: true }
96
- res[:reason] = :persist_failed unless res[:ok]
97
- res
158
+ new_val = fetch(key)
159
+ if old_val != new_val
160
+ notify_change(key, new_val, old_val)
161
+ @event_bus&.emit(:config_deleted, key: key.to_s, old_val: old_val)
162
+ end
163
+ res
164
+ end
98
165
  end
99
166
 
100
167
  # True only for scopes save! writes to disk; nil/false/:session/"session"/
@@ -170,7 +237,8 @@ module Rubik
170
237
 
171
238
  def notify_change(key, new_val, old_val)
172
239
  key_str = key.to_s
173
- @listeners.dup.each do |entry|
240
+ listeners = @monitor.synchronize { @listeners.dup }
241
+ listeners.each do |entry|
174
242
  prefix = entry[:prefix]
175
243
  matches = prefix.nil? || prefix.empty? || key_str == prefix || key_str.start_with?("#{prefix}.")
176
244
  next unless matches
@@ -185,18 +253,13 @@ module Rubik
185
253
  @event_bus&.emit(:config_changed, key: key_str, value: new_val, old_val: old_val)
186
254
  end
187
255
 
188
- def load_merged_config
189
- global_file = global_config_path
190
- project_file = project_config_path
191
-
192
- global_config = load_yaml(global_file)
193
- project_config = load_yaml(project_file)
194
-
195
- merged = deep_merge(deep_dup(DEFAULT_CONFIG), global_config)
196
- merged = deep_merge(merged, project_config)
256
+ def recompute_data!
257
+ merged = deep_dup(@defaults_layer || DEFAULT_CONFIG)
258
+ [@global_layer, @project_layer, @env_layer, @session_layer].each do |layer|
259
+ merged = deep_merge(merged, layer) if layer.is_a?(Hash)
260
+ end
197
261
 
198
- # If global or project config explicitly defines model roles, ensure stale default hosts are not retained
199
- [global_config, project_config].each do |cfg|
262
+ [@global_layer, @project_layer].each do |cfg|
200
263
  next unless cfg.is_a?(Hash)
201
264
 
202
265
  if cfg["models"].is_a?(Hash)
@@ -211,8 +274,21 @@ module Rubik
211
274
  merged["model"] = deep_dup(cfg["model"]) if cfg["model"].is_a?(Hash) && cfg["model"]["provider"] && cfg["model"]["name"]
212
275
  end
213
276
 
214
- validate_schema(merged)
215
- merged
277
+ @data = merged
278
+ end
279
+
280
+ def load_merged_config
281
+ @defaults_layer = deep_dup(DEFAULT_CONFIG)
282
+ @global_layer = load_yaml(global_config_path)
283
+ @global_layer = {} unless @global_layer.is_a?(Hash)
284
+ @project_layer = load_yaml(project_config_path)
285
+ @project_layer = {} unless @project_layer.is_a?(Hash)
286
+ @env_layer = EnvLoader.load_env(ENV, DEFAULT_CONFIG, @warnings)
287
+ @session_layer = {}
288
+
289
+ recompute_data!
290
+ validate_schema(@data)
291
+ @data
216
292
  end
217
293
  end
218
294
  end
@@ -69,7 +69,7 @@ module Rubik
69
69
  text.each_line do |line|
70
70
  if (m = line.match(/^error\[(E\d+)\]:(.*)$/))
71
71
  current_error = { code: m[1], message: m[2].strip, category: :type }
72
- elsif current_error && (m = line.match(/-->\s*([^:\s]+):(\d+):(\d+)/))
72
+ elsif current_error && (m = line.match(/-->\s*+([^:\s]++):(\d++):(\d++)/))
73
73
  entries << Entry.new(
74
74
  file: m[1],
75
75
  line: m[2],
@@ -125,7 +125,7 @@ module Rubik
125
125
  def parse_ts_js(text)
126
126
  entries = []
127
127
  text.each_line do |line|
128
- next unless (m = line.match(%r{^((?:[a-zA-Z]:[\\/])?[^(:\s]+)(?:\((\d+),(\d+)\)|:(\d+):(\d+))(?::\s*-\s*|:\s*|\s*-\s*|\s+)error(?:\s+(TS\d+))?:?(.*)$}i))
128
+ next unless (m = line.match(%r{^((?:[a-zA-Z]:[\\/])?[^(:\s]++)(?:\((\d++),(\d++)\)|:(\d++):(\d++))(?::\s*+-\s*+|:\s*+|\s*+-\s*+|\s++)error(?:\s++(TS\d++))?:?(.*)$}i))
129
129
 
130
130
  file = m[1]
131
131
  line_num = (m[2] || m[4]).to_i
@@ -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)
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "../../coeffects"
4
+ require_relative "../../tools/catalog"
4
5
 
5
6
  module Rubik
6
7
  module Orchestrator
@@ -15,8 +16,10 @@ module Rubik
15
16
  # budayıcının masaları yalnız kök/maestro düzlemine aittir —
16
17
  # subagent kayıt defterlerine ('self' klonu dahil, çünkü onun
17
18
  # filtresi yalnız spawn setini dışlar) asla kopyalanmaz. Orkestrasyon
18
- # belleği tek elde kalır.
19
- ROOT_ONLY_TOOLS = ["prune_context", "vakanuvis", "update_goal_ledger"].freeze
19
+ # belleği tek elde kalır. Derived from the Declarations: a tool with
20
+ # no subagent archetype is orchestrator-plane-only by definition, so
21
+ # the projection cannot drift from the allowlists.
22
+ ROOT_ONLY_TOOLS = Rubik::Tools::Catalog.orchestrator_only_tools.freeze
20
23
 
21
24
  def build(source_registry:, type_def:, child_ctx:, buffer:, parent_buffer:)
22
25
  return nil unless source_registry
@@ -35,7 +38,10 @@ module Rubik
35
38
 
36
39
  # Buffer-bound tools (rebuilt only when a branch buffer splits them
37
40
  # off the parent); everything else is context-rebind territory.
38
- BUFFER_BOUND_TOOLS = ["read_file", "write_file", "replace_file_content", "apply_buffer"].freeze
41
+ # Membership is declared on each tool's Declaration (buffer_bound:)
42
+ # and projected by Catalog; the rebuild itself stays here because
43
+ # branch splitting is an orchestrator concern, not the tool's.
44
+ BUFFER_BOUND_TOOLS = Rubik::Tools::Catalog.buffer_bound_tools.freeze
39
45
 
40
46
  # Buffer rebinding must preserve runtime-context coeffect reads
41
47
  # (rubik://goal/state, rubik://storage, subagent transcripts resolve
@@ -63,29 +69,14 @@ module Rubik
63
69
  # subagent-plane message carries its REAL sender id to the maestro;
64
70
  # invoke/manage swap so a nested spawn resolves the INSTANCE's task
65
71
  # token (issue #125) instead of the root turn's.
66
- # Class-matched (not name-matched): a plugin/dynamic tool registered
67
- # under the same name keeps its own implementation in every plane.
72
+ # Each tool owns its rebind_to(ctx) (locality of concern); the
73
+ # registry only decides WHEN. Tools without rebind_to (plugins,
74
+ # dynamic tools registered under the same name) keep their own
75
+ # implementation in every plane.
68
76
  def rebind_to_context(tool, ctx)
69
77
  return tool unless ctx.respond_to?(:get)
70
78
 
71
- case tool
72
- when Rubik::Tools::AskQuestionTool
73
- Rubik::Tools::AskQuestionTool.new(shell: nil, runtime_context: ctx)
74
- when Rubik::Tools::SendMessageTool
75
- Rubik::Tools::SendMessageTool.new(runtime_context: ctx)
76
- when Rubik::Tools::InvokeSubagentTool
77
- Rubik::Tools::InvokeSubagentTool.new(supervisor: supervisor_for(ctx), runtime_context: ctx)
78
- when Rubik::Tools::ManageSubagentsTool
79
- Rubik::Tools::ManageSubagentsTool.new(supervisor: supervisor_for(ctx), runtime_context: ctx)
80
- when Rubik::Tools::DefineSubagentTool
81
- Rubik::Tools::DefineSubagentTool.new(supervisor: supervisor_for(ctx), runtime_context: ctx)
82
- else
83
- tool
84
- end
85
- end
86
-
87
- def supervisor_for(ctx)
88
- Rubik::Coeffects.get(ctx, Rubik::Coeffects::SUBAGENT_SUPERVISOR)
79
+ tool.respond_to?(:rebind_to) ? tool.rebind_to(ctx) : tool
89
80
  end
90
81
  end
91
82
  end
@@ -115,13 +115,23 @@ module Rubik
115
115
  prov = provider if provider
116
116
 
117
117
  context_limit = @config.respond_to?(:fetch) ? @config.fetch("context.max_tokens", 32_768) : 32_768
118
+ effective_steps = (max_steps || @default_max_steps).to_i
119
+ child_config = if @config.is_a?(Rubik::Config)
120
+ @config.extend(
121
+ "agent.max_steps" => effective_steps,
122
+ "context.max_tokens" => context_limit
123
+ )
124
+ else
125
+ @config
126
+ end
127
+ child_ctx.provide(Rubik::Coeffects::CONFIG, child_config) if child_ctx.respond_to?(:provide) && defined?(Rubik::Coeffects::CONFIG)
118
128
 
119
129
  Instance.new(
120
130
  id: subagent_id, parent_id: parent_id, role: role_str, type_name: profile_snapshot.name,
121
131
  prompt: prompt_str, system_prompt: profile_snapshot.effective_system_prompt, workspace: workspace,
122
132
  model: effective_model, context: child_ctx, tool_registry: scoped_registry,
123
- provider: prov, buffer_manager: effective_buffer, max_steps: (max_steps || @default_max_steps).to_i,
124
- provider_gate: @provider_gate, root_dir: @root_dir, config: @config,
133
+ provider: prov, buffer_manager: effective_buffer, max_steps: effective_steps,
134
+ provider_gate: @provider_gate, root_dir: @root_dir, config: child_config,
125
135
  context_limit: context_limit, event_bus: @event_bus,
126
136
  transcript_storage: absorb_storage, owner_task: owner,
127
137
  prompt_reconstructible: prompt_reconstructible, profile_snapshot: profile_snapshot
@@ -1,7 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require_relative "../../tools/truncator"
4
- require_relative "../../tools/result"
3
+ require_relative "../../tools/result_normalizer"
5
4
  require_relative "../tool_timeout"
6
5
 
7
6
  module Rubik
@@ -11,7 +10,8 @@ module Rubik
11
10
  # every outcome — Result-backed, status-bearing, plain string, missing
12
11
  # tool, or raised error — is normalized into the Result contract so
13
12
  # status / exit_code / metadata survive truncation and reach the
14
- # canonical history row. Same classification as the root StepExecutor,
13
+ # canonical history row. Classification itself lives in
14
+ # Tools::ResultNormalizer, shared verbatim with the root StepExecutor,
15
15
  # so the two channels cannot drift.
16
16
  module ToolDispatch
17
17
  def dispatch_subagent_tool(tool, name, args)
@@ -22,10 +22,7 @@ module Rubik
22
22
  canonical_name: tool.respond_to?(:name) ? tool.name : name) do
23
23
  tool.execute(args)
24
24
  end
25
- max_chars = (cfg&.fetch("tools.max_output_chars", Rubik::Tools::Truncator::DEFAULT_MAX_CHARS) || Rubik::Tools::Truncator::DEFAULT_MAX_CHARS).to_i
26
- max_lines = (cfg&.fetch("tools.max_output_lines", Rubik::Tools::Truncator::DEFAULT_MAX_LINES) || Rubik::Tools::Truncator::DEFAULT_MAX_LINES).to_i
27
- strategy = Rubik::Tools::Truncator.resolve_strategy(cfg&.fetch("tools.truncation_strategy", Rubik::Tools::Truncator::DEFAULT_STRATEGY))
28
- normalize_tool_result(raw, name, max_chars: max_chars, max_lines: max_lines, strategy: strategy)
25
+ normalize_tool_result(raw, name)
29
26
  rescue Rubik::Orchestrator::ToolTimeout::BudgetExceeded => e
30
27
  Rubik::Orchestrator::ToolTimeout.emit_timeout_event(tool_name: name, budget_seconds: e.budget_seconds,
31
28
  elapsed_seconds: e.elapsed_seconds, context: @context)
@@ -37,48 +34,14 @@ module Rubik
37
34
 
38
35
  private
39
36
 
40
- def normalize_tool_result(raw, name, max_chars:, max_lines:, strategy: Rubik::Tools::Truncator::DEFAULT_STRATEGY)
41
- if raw.is_a?(Rubik::Tools::Result)
42
- trunc = Rubik::Tools::Truncator.truncate(raw.output, max_chars: max_chars, max_lines: max_lines, strategy: strategy)
43
- # Truncation only shortens the display text — status, exit code,
44
- # metadata and the original truncation flag all survive it.
45
- first_line = raw.output.to_s.lines.first.to_s.strip
46
- Rubik::Tools::Result.new(tool_name: raw.tool_name.to_s.empty? ? name : raw.tool_name,
47
- status: raw.status,
48
- error: raw.error || (raw.error? ? first_line : nil), exit_code: raw.exit_code,
49
- output: trunc[:text], duration_ms: raw.duration_ms,
50
- truncated: raw.truncated || trunc[:truncated], metadata: raw.metadata)
51
- elsif raw.respond_to?(:status) && raw.respond_to?(:output)
52
- out_str = raw.output.to_s
53
- trunc = Rubik::Tools::Truncator.truncate(out_str, max_chars: max_chars, max_lines: max_lines, strategy: strategy)
54
- first_line = out_str.lines.first.to_s.strip
55
- status = raw.status.to_sym
56
- Rubik::Tools::Result.new(tool_name: name, status: status,
57
- error: (raw.respond_to?(:error) && raw.error) || (status == :error ? first_line : nil),
58
- output: trunc[:text], truncated: trunc[:truncated],
59
- exit_code: raw.respond_to?(:exit_code) ? raw.exit_code : nil,
60
- metadata: raw.respond_to?(:metadata) ? raw.metadata : {})
61
- else
62
- out_str = raw.to_s
63
- trunc = Rubik::Tools::Truncator.truncate(out_str, max_chars: max_chars, max_lines: max_lines, strategy: strategy)
64
- status = classify_raw_string(raw, out_str)
65
- Rubik::Tools::Result.new(tool_name: name, status: status,
66
- error: status == :error ? out_str.lines.first.to_s.strip : nil,
67
- output: trunc[:text], truncated: trunc[:truncated])
68
- end
69
- end
70
-
71
- # Root-parity string classification (arch scan card 5, review F1): the
72
- # same lexicon as StepExecutor#normalize_raw_output's else branch —
73
- # error?/failed? predicates, then the shared ERROR_PREFIXES table.
74
- # Without this, a bare "Error: ..." string reads status=ok in subagent
75
- # history while the root plane honestly reports :error.
76
- def classify_raw_string(raw, out_str)
77
- return :error if raw.respond_to?(:error?) && raw.error?
78
- return :error if raw.respond_to?(:failed?) && raw.failed?
79
- return :error if raw.is_a?(String) && Rubik::Orchestrator::StepExecutor::ERROR_PREFIXES.any? { |pfx| out_str.start_with?(pfx) }
80
-
81
- :ok
37
+ # Thin delegator: carrier classification and truncation limits live
38
+ # in Tools::ResultNormalizer — the single home both orchestrator
39
+ # planes share, so the channels cannot drift. The
40
+ # subagent plane passes no call_id/duration_ms (nothing measured
41
+ # here); wrapping stays local so a normalize bug is contained into an
42
+ # error result by dispatch_subagent_tool's rescue.
43
+ def normalize_tool_result(raw, name)
44
+ Rubik::Tools::ResultNormalizer.normalize(raw, tool_name: name, config: @config)
82
45
  end
83
46
 
84
47
  def error_result(name, text, error: nil)
@@ -56,13 +56,18 @@ module Rubik
56
56
  end
57
57
 
58
58
  # Registry-canonical finish detection: a call is the finish call when
59
- # the registry resolves it to the finish tool — an unregistered case
60
- # variant ("Finish") downcases to finish instead of dispatching an
61
- # unknown tool. A nil registry degrades to the downcase compare.
59
+ # the registry resolves it to a terminal tool (Declaration terminal:,
60
+ # projected by Catalog). The name compare stays as the duck-typed
61
+ # fallback — fake/dynamic registries can resolve plain objects whose
62
+ # class carries no Declaration (a terminal?-less "finish" must still
63
+ # complete the turn, or the loop waits forever); an unregistered case
64
+ # variant ("Finish") downcases to finish too.
62
65
  def finish_call?(tool_registry, tool_call)
63
66
  t_name = tool_call["tool"] || tool_call[:tool]
64
67
  resolved = tool_registry.respond_to?(:get) ? tool_registry.get(t_name) : nil
65
- (resolved ? resolved.name : t_name.to_s.downcase) == "finish"
68
+ return true if resolved.respond_to?(:terminal?) && resolved.terminal?
69
+
70
+ (resolved ? resolved.name : t_name).to_s.downcase == "finish"
66
71
  end
67
72
  end
68
73