rubik 0.7.0 → 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 (57) hide show
  1. checksums.yaml +4 -4
  2. data/ATTRIBUTION.md +1 -1
  3. data/CHANGELOG.md +177 -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 +6 -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/collector.rb +8 -2
  15. data/lib/rubik/diagnostics/parser.rb +2 -2
  16. data/lib/rubik/lsp/client.rb +26 -6
  17. data/lib/rubik/lsp/manager.rb +24 -6
  18. data/lib/rubik/orchestrator/lsp_feedback.rb +2 -1
  19. data/lib/rubik/orchestrator/step_executor.rb +12 -59
  20. data/lib/rubik/orchestrator/subagent/scoped_registry.rb +14 -23
  21. data/lib/rubik/orchestrator/subagent/spawn_transaction.rb +12 -2
  22. data/lib/rubik/orchestrator/subagent/tool_dispatch.rb +12 -49
  23. data/lib/rubik/orchestrator/turn_executor.rb +9 -4
  24. data/lib/rubik/repl/commands/lsp.rb +13 -1
  25. data/lib/rubik/repl/commands/workspace.rb +14 -8
  26. data/lib/rubik/repl/lifecycle.rb +11 -0
  27. data/lib/rubik/repl/service_catalog.rb +2 -1
  28. data/lib/rubik/repl/shell.rb +1 -0
  29. data/lib/rubik/runtime/context.rb +12 -14
  30. data/lib/rubik/runtime/discovery.rb +1 -0
  31. data/lib/rubik/sandbox/runner.rb +28 -13
  32. data/lib/rubik/storage/render.rb +1 -1
  33. data/lib/rubik/storage/vakanuvis/distill_gate.rb +3 -3
  34. data/lib/rubik/storage/vakanuvis/harness.rb +4 -65
  35. data/lib/rubik/storage/vakanuvis/orientation.rb +1 -2
  36. data/lib/rubik/storage/vakanuvis/recall.rb +84 -0
  37. data/lib/rubik/storage/vakanuvis.rb +1 -0
  38. data/lib/rubik/tools/base.rb +34 -0
  39. data/lib/rubik/tools/builtins/define_subagent.rb +6 -0
  40. data/lib/rubik/tools/builtins/dmesg.rb +4 -4
  41. data/lib/rubik/tools/builtins/files.rb +18 -24
  42. data/lib/rubik/tools/builtins/goal_ledger.rb +1 -1
  43. data/lib/rubik/tools/builtins/grep.rb +6 -6
  44. data/lib/rubik/tools/builtins/interactive.rb +6 -0
  45. data/lib/rubik/tools/builtins/lifecycle.rb +2 -1
  46. data/lib/rubik/tools/builtins/lsp.rb +127 -110
  47. data/lib/rubik/tools/builtins/pruner.rb +1 -1
  48. data/lib/rubik/tools/builtins/send_message.rb +6 -0
  49. data/lib/rubik/tools/builtins/subagent.rb +12 -0
  50. data/lib/rubik/tools/builtins/vakanuvis.rb +1 -1
  51. data/lib/rubik/tools/catalog.rb +20 -1
  52. data/lib/rubik/tools/declaration.rb +15 -2
  53. data/lib/rubik/tools/registry.rb +6 -5
  54. data/lib/rubik/tools/result_normalizer.rb +115 -0
  55. data/lib/rubik/tools/truncator.rb +3 -3
  56. data/lib/rubik/version.rb +1 -1
  57. metadata +7 -1
@@ -0,0 +1,108 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rubik
4
+ class Config
5
+ # Scoped child configuration (AGENTS.md §1.C Unified Context Paradigm).
6
+ # Created via parent_config.extend(overrides = {}).
7
+ # Reads fall back to the parent config unless overridden in the child.
8
+ # Writes modify only the child's local scope, never polluting parent state.
9
+ # Disk persistence from child configs is fail-closed (raises ArgumentError).
10
+ class Scoped < Config
11
+ attr_reader :parent, :overrides
12
+
13
+ # rubocop:disable-next Lint/MissingSuper
14
+ def initialize(parent, overrides = {})
15
+ @parent = parent
16
+ @root_dir = parent.root_dir
17
+ @home_dir = parent.home_dir
18
+ @monitor = Monitor.new
19
+ @warnings = []
20
+ @listeners = []
21
+ @event_bus = parent.event_bus
22
+ @overrides = {}
23
+ return unless overrides.is_a?(Hash)
24
+
25
+ overrides.each do |k, v|
26
+ typed = v.is_a?(Hash) ? deep_stringify_keys(deep_dup(v)) : Schema.coerce(k.to_s, parse_scalar_value(deep_dup(v)))
27
+ Schema.validate_value!(k, typed, strict: true)
28
+ # Hash overrides get the same leaf coercion + validation that
29
+ # dotted-key writes go through, so extend(ui: {verbosity: 'x'})
30
+ # is as strict as set('ui.verbosity', 'x').
31
+ if typed.is_a?(Hash)
32
+ Schema.coerce_nested!(typed, k.to_s)
33
+ section = DEFAULT_CONFIG[k.to_s]
34
+ validate_schema(typed, section, k.to_s) if section.is_a?(Hash) && !section.empty?
35
+ end
36
+ deep_set_key(@overrides, k.to_s, typed)
37
+ end
38
+ end
39
+
40
+ def fetch(key, default = nil)
41
+ @monitor.synchronize do
42
+ keys = key.to_s.split(".")
43
+ val = keys.reduce(@overrides) do |acc, k|
44
+ break nil unless acc.is_a?(Hash) && acc.key?(k)
45
+
46
+ acc[k]
47
+ end
48
+ return val unless val.nil?
49
+
50
+ @parent.fetch(key, default)
51
+ end
52
+ end
53
+
54
+ def [](key)
55
+ fetch(key)
56
+ end
57
+
58
+ def set(key, value, persist: nil)
59
+ raise ArgumentError, "Scoped child configurations cannot persist to disk (scope: #{persist.inspect})" if persisting?(persist)
60
+
61
+ @monitor.synchronize do
62
+ old_val = fetch(key)
63
+ typed_val = parse_scalar_value(value)
64
+ typed_val = Schema.coerce(key, typed_val)
65
+ Schema.validate_value!(key, typed_val, strict: true)
66
+ if typed_val.is_a?(Hash)
67
+ typed_val = deep_dup(typed_val)
68
+ Schema.coerce_nested!(typed_val, key.to_s)
69
+ section = DEFAULT_CONFIG[key.to_s]
70
+ validate_schema(typed_val, section, key.to_s) if section.is_a?(Hash) && !section.empty?
71
+ end
72
+ deep_set_key(@overrides, key, typed_val)
73
+ notify_change(key, typed_val, old_val) if old_val != typed_val
74
+ { ok: true }
75
+ end
76
+ end
77
+
78
+ def delete(key, persist: nil)
79
+ raise ArgumentError, "Scoped child configurations cannot persist to disk" if persisting?(persist)
80
+
81
+ @monitor.synchronize do
82
+ old_val = fetch(key)
83
+ deep_delete(@overrides, key)
84
+ new_val = fetch(key)
85
+ if old_val != new_val
86
+ notify_change(key, new_val, old_val)
87
+ @event_bus&.emit(:config_deleted, key: key.to_s, old_val: old_val)
88
+ end
89
+ { ok: true }
90
+ end
91
+ end
92
+
93
+ def model_spec(role = :default)
94
+ role_str = role.to_s.downcase
95
+ spec = fetch("models.#{role_str}")
96
+ return spec if spec.is_a?(Hash) && spec["provider"] && spec["name"]
97
+
98
+ @parent.model_spec(role)
99
+ end
100
+
101
+ def data
102
+ @monitor.synchronize do
103
+ deep_merge(@parent.data, @overrides)
104
+ end
105
+ end
106
+ end
107
+ end
108
+ end
@@ -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
@@ -16,7 +16,11 @@ module Rubik
16
16
 
17
17
  def initialize(lsp_manager: nil, root_dir: Dir.pwd)
18
18
  @lsp_manager = lsp_manager
19
- @root_dir = File.expand_path(root_dir)
19
+ @root_dir = if root_dir.to_s.match?(%r{\A[a-zA-Z]:[\\/]})
20
+ root_dir.to_s.tr("\\", "/")
21
+ else
22
+ File.expand_path(root_dir)
23
+ end
20
24
  @entries = []
21
25
  @mutex = Mutex.new
22
26
  end
@@ -193,7 +197,9 @@ module Rubik
193
197
 
194
198
  norm_path = path.to_s.tr("\\", "/")
195
199
  norm_root = @root_dir.to_s.tr("\\", "/")
196
- norm_path.sub(%r{^#{Regexp.escape(norm_root)}/}, "")
200
+ pattern = %r{^#{Regexp.escape(norm_root)}/}
201
+ pattern = Regexp.new(pattern.source, Regexp::IGNORECASE) if Rubik::Platform.windows? || norm_root.match?(%r{\A[a-zA-Z]:/})
202
+ norm_path.sub(pattern, "")
197
203
  end
198
204
  end
199
205
  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
@@ -25,7 +25,7 @@ module Rubik
25
25
  "zig" => "zls",
26
26
  "c" => "clangd",
27
27
  "cpp" => "clangd",
28
- "python" => "pylsp",
28
+ "python" => "ruff server",
29
29
  "ruby" => "typeprof --lsp --stdio",
30
30
  "typescript" => "typescript-language-server --stdio",
31
31
  "javascript" => "typescript-language-server --stdio",
@@ -91,6 +91,8 @@ module Rubik
91
91
  def start
92
92
  return false unless available?
93
93
 
94
+ stop if alive? || @wait_thr&.alive? || @reader_alive
95
+
94
96
  @document_mutex.synchronize do
95
97
  @req_id = 0
96
98
  @open_documents.clear
@@ -114,7 +116,7 @@ module Rubik
114
116
 
115
117
  cmd_parts[0] = resolved_bin if resolved_bin
116
118
 
117
- @stdin, @stdout, @stderr, @wait_thr = Open3.popen3(*cmd_parts, chdir: @root_dir)
119
+ @stdin, @stdout, @stderr, @wait_thr = Open3.popen3(sanitized_spawn_env, *cmd_parts, chdir: @root_dir)
118
120
  # Binary mode: LSP framing is byte-exact. Text-mode pipes on Windows
119
121
  # translate CRLF→LF on read, so Content-Length counts and read(len)
120
122
  # disagree and the JSON body arrives truncated (the reader's old
@@ -131,10 +133,18 @@ module Rubik
131
133
  # server itself mid-write; drain continuously, discard content.
132
134
  @stderr_drain = Rubik::Platform::IoDrain.start(@stderr)
133
135
 
136
+ root_uri = Rubik::Platform.to_file_uri(@root_dir)
134
137
  init_res = send_request("initialize", {
135
138
  processId: Process.pid,
136
- rootUri: Rubik::Platform.to_file_uri(@root_dir),
139
+ rootUri: root_uri,
140
+ workspaceFolders: [
141
+ { uri: root_uri, name: File.basename(@root_dir) }
142
+ ],
137
143
  capabilities: {
144
+ workspace: {
145
+ workspaceFolders: true,
146
+ configuration: true
147
+ },
138
148
  textDocument: {
139
149
  hover: { contentFormat: ["markdown", "plaintext"] },
140
150
  synchronization: {
@@ -695,11 +705,13 @@ module Rubik
695
705
  }.freeze
696
706
  when Hash
697
707
  save = value["save"]
708
+ change = (value["change"] || 0).to_i.clamp(0, 2)
709
+ open_close = value.key?("openClose") ? (value["openClose"] == true) : change.positive?
698
710
  {
699
711
  source: :options,
700
- open_close: value["openClose"] == true,
701
- change: (value["change"] || 0).to_i.clamp(0, 2),
702
- save: !!save,
712
+ open_close: open_close,
713
+ change: change,
714
+ save: !save.nil? && save != false,
703
715
  include_text: save.is_a?(Hash) && save["includeText"] == true
704
716
  }.freeze
705
717
  else
@@ -773,6 +785,14 @@ module Rubik
773
785
  end
774
786
  false
775
787
  end
788
+
789
+ def sanitized_spawn_env
790
+ env = {}
791
+ ENV.each_key do |k|
792
+ env[k] = nil if k.start_with?("BUNDLE_", "BUNDLER_") || ["RUBYOPT", "RUBYLIB"].include?(k)
793
+ end
794
+ env
795
+ end
776
796
  end
777
797
  end
778
798
  end
@@ -55,6 +55,7 @@ module Rubik
55
55
  @healthy_since = {}
56
56
  @recovery_errors = {}
57
57
  @registered_disposable_langs = {}
58
+ @client_inverses = {}
58
59
  @monitor = Monitor.new
59
60
  end
60
61
 
@@ -176,6 +177,8 @@ module Rubik
176
177
  else
177
178
  record_crash(lang_str)
178
179
  stop_client_safely(client)
180
+ @clients.delete(lang_str)
181
+ unregister_client_unlocked(lang_str)
179
182
  failure = Runtime::DiagnosticEngine.diagnose(
180
183
  cmd: ServerCommand.display(client.server_cmd),
181
184
  exit_code: 1,
@@ -238,6 +241,15 @@ module Rubik
238
241
  client.did_save(file_path, content)
239
242
  end
240
243
 
244
+ def did_close_file(file_path)
245
+ return false unless enabled?
246
+
247
+ client = client_for(file_path)
248
+ return false unless client&.running
249
+
250
+ client.did_close(file_path)
251
+ end
252
+
241
253
  def sync_buffer_file_if_needed(file_path, buffer_manager)
242
254
  return false unless enabled? && buffer_manager
243
255
 
@@ -455,24 +467,30 @@ module Rubik
455
467
  end
456
468
 
457
469
  def register_client_unlocked(lang, client)
470
+ lang_str = lang.to_s.downcase
458
471
  effective_ctx = @context || @runtime_manager&.context
459
472
  return unless effective_ctx
460
473
 
461
- effective_ctx.provide("lsp:#{lang}", client)
462
- return if @registered_disposable_langs[lang] == effective_ctx.object_id
474
+ effective_ctx.provide("lsp:#{lang_str}", client)
475
+ return if @registered_disposable_langs[lang_str] == effective_ctx.object_id
463
476
 
464
- @registered_disposable_langs[lang] = effective_ctx.object_id
465
- effective_ctx.register_disposable do
466
- current = @clients[lang]
477
+ inverse = effective_ctx.register_disposable do
478
+ current = @clients[lang_str]
467
479
  current.stop if current&.running
468
480
  end
481
+ @registered_disposable_langs[lang_str] = effective_ctx.object_id
482
+ @client_inverses[lang_str] = inverse
469
483
  end
470
484
 
471
485
  def unregister_client_unlocked(lang)
472
486
  lang_str = lang.to_s.downcase
473
487
  @registered_disposable_langs.delete(lang_str)
488
+ inverse = @client_inverses.delete(lang_str)
474
489
  effective_ctx = @context || @runtime_manager&.context
475
- effective_ctx&.unprovide("lsp:#{lang_str}") if effective_ctx.respond_to?(:unprovide)
490
+ return unless effective_ctx
491
+
492
+ effective_ctx.unprovide("lsp:#{lang_str}") if effective_ctx.respond_to?(:unprovide)
493
+ effective_ctx.unregister_disposable(inverse) if inverse && effective_ctx.respond_to?(:unregister_disposable)
476
494
  end
477
495
 
478
496
  def stop_client_safely(client)
@@ -36,8 +36,9 @@ module Rubik
36
36
  end
37
37
 
38
38
  def append_diagnostics(deps, written_file, tool_result)
39
+ timeout = deps.lsp_manager&.config&.fetch("lsp.feedback_timeout", 0.5) || 0.5
39
40
  snapshot = if deps.lsp_manager.respond_to?(:wait_for_diagnostics)
40
- deps.lsp_manager.wait_for_diagnostics(written_file, timeout: 0.2)
41
+ deps.lsp_manager.wait_for_diagnostics(written_file, timeout: timeout)
41
42
  else
42
43
  deps.lsp_manager.diagnostics_snapshot_for(written_file)
43
44
  end