rubik 0.9.0 → 0.10.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 (130) hide show
  1. checksums.yaml +4 -4
  2. data/ATTRIBUTION.md +1 -1
  3. data/CHANGELOG.md +250 -43
  4. data/README.md +5 -1
  5. data/lib/rubik/adapter/base.rb +21 -1
  6. data/lib/rubik/adapter/generic.rb +0 -14
  7. data/lib/rubik/adapter/node.rb +2 -0
  8. data/lib/rubik/adapter/process.rb +28 -67
  9. data/lib/rubik/ast/treesitter/zig_walker.rb +15 -2
  10. data/lib/rubik/benchmark/vakanuvis_adoption.rb +10 -3
  11. data/lib/rubik/buffer/apply_contract.rb +3 -3
  12. data/lib/rubik/buffer/apply_transaction.rb +165 -0
  13. data/lib/rubik/buffer/manager.rb +26 -120
  14. data/lib/rubik/cli/workspace_trust.rb +16 -0
  15. data/lib/rubik/config/deep_ops.rb +4 -1
  16. data/lib/rubik/config/defaults.rb +29 -3
  17. data/lib/rubik/config/schema.rb +8 -0
  18. data/lib/rubik/config/secret_policy.rb +197 -0
  19. data/lib/rubik/config/store.rb +14 -0
  20. data/lib/rubik/config.rb +11 -0
  21. data/lib/rubik/diagnostics/collector.rb +0 -9
  22. data/lib/rubik/errors.rb +15 -0
  23. data/lib/rubik/event_bus.rb +2 -1
  24. data/lib/rubik/kernel/dispatcher.rb +16 -11
  25. data/lib/rubik/kernel/unit.rb +4 -1
  26. data/lib/rubik/llm/registry.rb +12 -9
  27. data/lib/rubik/llm/router.rb +2 -5
  28. data/lib/rubik/log.rb +23 -1
  29. data/lib/rubik/lsp/client.rb +152 -445
  30. data/lib/rubik/lsp/document_store.rb +209 -0
  31. data/lib/rubik/lsp/manager.rb +14 -10
  32. data/lib/rubik/lsp/transport.rb +365 -0
  33. data/lib/rubik/mcp/boot_lifecycle.rb +6 -2
  34. data/lib/rubik/mcp/boot_run.rb +190 -0
  35. data/lib/rubik/mcp/client.rb +4 -3
  36. data/lib/rubik/mcp/manager.rb +46 -165
  37. data/lib/rubik/mcp/transport/stdio.rb +55 -10
  38. data/lib/rubik/orchestrator/auto_apply.rb +4 -3
  39. data/lib/rubik/orchestrator/continuation_manager.rb +3 -22
  40. data/lib/rubik/orchestrator/goal_session.rb +519 -0
  41. data/lib/rubik/orchestrator/loop.rb +28 -47
  42. data/lib/rubik/orchestrator/maestro_gate.rb +5 -7
  43. data/lib/rubik/orchestrator/provider_recovery.rb +4 -2
  44. data/lib/rubik/orchestrator/provider_resolver.rb +4 -2
  45. data/lib/rubik/orchestrator/resume_window.rb +96 -0
  46. data/lib/rubik/orchestrator/shell_deps.rb +16 -0
  47. data/lib/rubik/orchestrator/stream_manager.rb +2 -1
  48. data/lib/rubik/orchestrator/subagent/deferred_spec.rb +4 -1
  49. data/lib/rubik/orchestrator/subagent/instance.rb +11 -12
  50. data/lib/rubik/orchestrator/subagent/journal.rb +2 -1
  51. data/lib/rubik/orchestrator/subagent/lifecycle.rb +3 -1
  52. data/lib/rubik/orchestrator/subagent/questioner.rb +24 -7
  53. data/lib/rubik/orchestrator/subagent/reaper.rb +3 -5
  54. data/lib/rubik/orchestrator/subagent/resilience.rb +4 -2
  55. data/lib/rubik/orchestrator/subagent/result_archive.rb +0 -4
  56. data/lib/rubik/orchestrator/subagent/run_cycle.rb +2 -7
  57. data/lib/rubik/orchestrator/subagent/spawn_transaction.rb +11 -2
  58. data/lib/rubik/orchestrator/subagent/step_runner.rb +11 -3
  59. data/lib/rubik/orchestrator/subagent/teardown.rb +4 -0
  60. data/lib/rubik/orchestrator/subagent/transcript_formatter.rb +2 -1
  61. data/lib/rubik/orchestrator/subagent/type_definition.rb +0 -4
  62. data/lib/rubik/orchestrator/tool_timeout.rb +121 -1
  63. data/lib/rubik/orchestrator.rb +1 -0
  64. data/lib/rubik/platform/io_drain.rb +2 -1
  65. data/lib/rubik/platform/process.rb +144 -54
  66. data/lib/rubik/platform.rb +17 -1
  67. data/lib/rubik/plugin/manager.rb +2 -1
  68. data/lib/rubik/plugin/storage.rb +20 -29
  69. data/lib/rubik/repl/commands/agent_context.rb +9 -8
  70. data/lib/rubik/repl/commands/agent_execution.rb +20 -502
  71. data/lib/rubik/repl/commands/agent_models.rb +4 -3
  72. data/lib/rubik/repl/commands/agent_providers.rb +43 -2
  73. data/lib/rubik/repl/commands/base.rb +47 -2
  74. data/lib/rubik/repl/commands/buffer.rb +6 -5
  75. data/lib/rubik/repl/commands/lsp.rb +3 -2
  76. data/lib/rubik/repl/commands/pruner.rb +2 -1
  77. data/lib/rubik/repl/commands/secrets.rb +151 -0
  78. data/lib/rubik/repl/commands/workspace.rb +60 -150
  79. data/lib/rubik/repl/commands/workspace_approval.rb +209 -0
  80. data/lib/rubik/repl/config_wiring.rb +3 -3
  81. data/lib/rubik/repl/hooks.rb +2 -1
  82. data/lib/rubik/repl/input_execution.rb +158 -76
  83. data/lib/rubik/repl/input_loop.rb +3 -2
  84. data/lib/rubik/repl/lifecycle.rb +82 -204
  85. data/lib/rubik/repl/notice_router.rb +319 -0
  86. data/lib/rubik/repl/paste_support.rb +3 -1
  87. data/lib/rubik/repl/presentation.rb +5 -3
  88. data/lib/rubik/repl/pruner/gate.rb +3 -1
  89. data/lib/rubik/repl/pruner/harness.rb +2 -1
  90. data/lib/rubik/repl/shell.rb +4 -3
  91. data/lib/rubik/repl/turn_recorder.rb +6 -5
  92. data/lib/rubik/runtime/discovery.rb +3 -2
  93. data/lib/rubik/runtime/loop_service.rb +4 -3
  94. data/lib/rubik/runtime/manifest_store.rb +124 -0
  95. data/lib/rubik/runtime/overlay_guard.rb +127 -0
  96. data/lib/rubik/runtime/overlay_storage.rb +269 -272
  97. data/lib/rubik/runtime/task_manager.rb +71 -27
  98. data/lib/rubik/runtime.rb +1 -0
  99. data/lib/rubik/sandbox/driver/docker.rb +5 -1
  100. data/lib/rubik/sandbox/runner.rb +16 -15
  101. data/lib/rubik/security/allowlist.rb +167 -0
  102. data/lib/rubik/security/audit_log.rb +72 -0
  103. data/lib/rubik/security/classifier/classifier.rb +8 -0
  104. data/lib/rubik/security/command_gate.rb +591 -0
  105. data/lib/rubik/security/guard.rb +94 -1077
  106. data/lib/rubik/security/path_policy.rb +117 -0
  107. data/lib/rubik/security/secret_store.rb +463 -0
  108. data/lib/rubik/security/synthesis_gate.rb +297 -0
  109. data/lib/rubik/security.rb +5 -0
  110. data/lib/rubik/session/manager.rb +7 -1
  111. data/lib/rubik/skills/manager.rb +2 -3
  112. data/lib/rubik/storage/ranking.rb +113 -0
  113. data/lib/rubik/storage/search.rb +49 -0
  114. data/lib/rubik/storage/store.rb +15 -112
  115. data/lib/rubik/storage/transcript_indexer.rb +2 -3
  116. data/lib/rubik/storage/vakanuvis/harness.rb +2 -3
  117. data/lib/rubik/tools/base.rb +22 -0
  118. data/lib/rubik/tools/builtins/files.rb +3 -15
  119. data/lib/rubik/tools/builtins/grep.rb +3 -9
  120. data/lib/rubik/tools/builtins/lifecycle.rb +96 -92
  121. data/lib/rubik/tools/builtins/synthesis.rb +3 -0
  122. data/lib/rubik/tools/lifecycle_rollbacks.rb +100 -0
  123. data/lib/rubik/tools/native_search.rb +2 -1
  124. data/lib/rubik/tools/truncator.rb +73 -36
  125. data/lib/rubik/ui/banner.rb +4 -3
  126. data/lib/rubik/ui/spinner.rb +3 -1
  127. data/lib/rubik/ui/statusline.rb +6 -5
  128. data/lib/rubik/version.rb +1 -1
  129. data/lib/rubik.rb +1 -2
  130. metadata +23 -1
@@ -9,6 +9,8 @@ require_relative "../platform"
9
9
  require_relative "../uris"
10
10
  require_relative "layout"
11
11
  require_relative "folding"
12
+ require_relative "ranking"
13
+ require_relative "search"
12
14
 
13
15
  module Rubik
14
16
  module Storage
@@ -32,17 +34,6 @@ module Rubik
32
34
  ID_PATTERN = /\A([a-z]+)\.(\d+)\.([0-9a-f]{16})\z/
33
35
  HASH_PREFIX_MIN = 8
34
36
  REF_PATTERN = /\A[a-zA-Z0-9._-]+\z/
35
- # BM25-lite (vakanüvis-v2 §4-V8): klasik Okapi değerleri — k1 terim
36
- # doygunluğu, b uzunluk normalizasyonu ağırlığı.
37
- BM25_K1 = 1.2
38
- BM25_B = 0.75
39
- # Alan kademeli bonus (issue #99 P3): BM25 birincil kalır; başlıkta
40
- # geçen sorgu terimi etikette geçene, o da yalnız gövdede geçene
41
- # üstünlük kurar. Terim başına birimdir ve tipik idf katkısının
42
- # altındadır — maddesel BM25 farklarını ezmez, sadece eşit-yakın
43
- # skorları alan bilgisiyle kırar.
44
- TITLE_TIER_BONUS = 1.0
45
- TAGS_TIER_BONUS = 0.5
46
37
 
47
38
  Summary = Struct.new(:id, :row, :title, :status, :updated_at, :tags, keyword_init: true)
48
39
 
@@ -139,16 +130,16 @@ module Rubik
139
130
  # kelimeli sorgular kelimesi kelimesine eşleşmediği için 0 sonuç
140
131
  # dönüyordu (js-tangram olay raporu 2026-10-04, olay #2 — "indeks
141
132
  # bayatlığı" değil, eşleştirme semantiğiydi). Tek terimli sorgular
142
- # eski davranışın birebir aynısı.
143
- tokens = Folding.fold(query).split
133
+ # eski davranışın birebir aynısı. Tokenizasyon ve AND eşiği
134
+ # Search'te (issue #473) — burada yalnız corpus montajı.
135
+ tokens = Search.tokens(query)
144
136
  return [] if tokens.empty?
145
137
 
146
138
  @monitor.synchronize do
147
139
  matched = resolve_types(type).flat_map do |t|
148
140
  records = load_records(t)
149
141
  haystacks = haystacks_for(t, records)
150
- records.each_index.select { |i| tokens.all? { |token| haystacks[i].include?(token) } }
151
- .map { |i| records[i] }
142
+ Search.matching_indices(records, haystacks, tokens).map { |i| records[i] }
152
143
  end
153
144
  matched.sort_by { |r| [r["type"].to_s, r["row"].to_i] }
154
145
  end
@@ -169,7 +160,7 @@ module Rubik
169
160
  # (herhangi bir terimi taşıyan kayıt) — fallback recall içindir;
170
161
  # skorlama iki ducte de aynıdır, default davranış birebir korunur.
171
162
  def search_ranked(query:, type: nil, require_all: true)
172
- tokens = Folding.fold(query).split
163
+ tokens = Search.tokens(query)
173
164
  return [] if tokens.empty?
174
165
 
175
166
  @monitor.synchronize do
@@ -184,90 +175,10 @@ module Rubik
184
175
  end
185
176
  return [] if corpus.empty?
186
177
 
187
- total = corpus.sum { |c| c[:records].size }
188
- avgdl = corpus.sum { |c| c[:haystacks].sum(&:bytesize) }.fdiv(total)
189
- dfs = tokens.each_index.map { |ti| corpus.sum { |c| c[:has][ti].count(true) } }
190
-
191
- gate = ranked_gate(require_all)
192
- scored = corpus.flat_map do |c|
193
- c[:records].each_index.select { |i| gate.call(c[:has], i) }.map do |i|
194
- score = tokens.each_with_index.sum do |token, ti|
195
- df = dfs[ti]
196
- next 0.0 if df.zero?
197
-
198
- # PERF: count_occurrences using String#index avoids Array allocation of String#scan
199
- tf = count_occurrences(c[:haystacks][i], token)
200
- next 0.0 if tf.zero?
201
-
202
- idf = Math.log(((total - df + 0.5) / (df + 0.5)) + 1)
203
- dl = c[:haystacks][i].bytesize
204
- idf * (tf * (BM25_K1 + 1)) / (tf + (BM25_K1 * (1 - BM25_B + (BM25_B * dl / avgdl))))
205
- end
206
- # PERF: pass cached folded title and tags to avoid String folding & array join allocations per score
207
- f_title, f_tags = c[:folded_fields][i]
208
- [score + field_tier_bonus(tokens, f_title, f_tags), c[:records][i]]
209
- end
210
- end
211
- ordered = scored.sort do |(score_a, rec_a), (score_b, rec_b)|
212
- (score_b <=> score_a).nonzero? ||
213
- (rec_b["updated_at"].to_s <=> rec_a["updated_at"].to_s).nonzero? ||
214
- (rec_a["type"].to_s <=> rec_b["type"].to_s).nonzero? ||
215
- (rec_a["row"].to_i <=> rec_b["row"].to_i)
216
- end
217
- ordered.map { |_score, record| record }
218
- end
219
- end
220
-
221
- # Aday eşiği: require_all (AND — default, recall) ya da OR
222
- # gevşetmesi (fallback — issue #99 P2).
223
- def ranked_gate(require_all)
224
- if require_all
225
- ->(has, i) { has.all? { |row| row[i] } }
226
- else
227
- ->(has, i) { has.any? { |row| row[i] } }
178
+ Ranking.rank(tokens: tokens, corpus: corpus, require_all: require_all)
228
179
  end
229
180
  end
230
181
 
231
- # PERF: Zero-allocation string occurrence counting via String#index loop.
232
- # Replaces String#scan(token).size to avoid array allocation per matched term.
233
- def count_occurrences(haystack, token)
234
- return 0 if token.empty?
235
-
236
- count = 0
237
- offset = 0
238
- token_len = token.length
239
- while (idx = haystack.index(token, offset))
240
- count += 1
241
- offset = idx + token_len
242
- end
243
- count
244
- end
245
-
246
- # Terim başına alan izi: katlanmış başlıkta geçen terim +1.0,
247
- # yalnız katlanmış etiketlerde geçen +0.5, gövde izi 0 — bkz.
248
- # TITLE_TIER_BONUS/TAGS_TIER_BONUS. Yalnız AND eşiğini geçen
249
- # kayıtlar için hesaplanır (ek tarama yok).
250
- # PERF: accepts pre-folded title & tags strings or fallback record for backward compatibility.
251
- def field_tier_bonus(tokens, title_or_record, tags = nil)
252
- if tags.nil? && title_or_record.is_a?(Hash)
253
- title = Folding.fold(title_or_record["title"])
254
- tags = Folding.fold(Array(title_or_record["tags"]).join("\n"))
255
- else
256
- title = title_or_record.to_s
257
- tags = tags.to_s
258
- end
259
-
260
- sum = 0.0
261
- tokens.each do |token|
262
- if title.include?(token)
263
- sum += TITLE_TIER_BONUS
264
- elsif tags.include?(token)
265
- sum += TAGS_TIER_BONUS
266
- end
267
- end
268
- sum
269
- end
270
-
271
182
  def set_ref(name, id)
272
183
  name = name.to_s
273
184
  raise ArgumentError, "invalid ref name '#{name}'" unless name.match?(REF_PATTERN)
@@ -448,31 +359,23 @@ module Rubik
448
359
  # tek katlama kuralı, folding.rb): parse cache girdisinde tembel
449
360
  # memoize edilir — sorgu başına 1 MB'lık dizgi kurulumu tekrarlamaz.
450
361
  # Kayıt kümesi paylaşımlı olduğundan samanlıklar da dondurulmuş
451
- # paylaşılır (include?/scan/bytesize mutasyon yapmaz).
362
+ # paylaşılır (include?/scan/bytesize mutasyon yapmaz). Samanlık
363
+ # kurulumu Search'te (issue #473) — burada yalnız sorgu başına
364
+ # memoize disiplini.
452
365
  def haystacks_for(type, records)
453
366
  entry = @records_cache[type]
454
- return records.map { |r| haystack_of(r) } unless entry
367
+ return records.map { |r| Search.haystack_of(r) } unless entry
455
368
 
456
- entry[:haystacks] ||= records.map { |r| haystack_of(r) }.freeze
369
+ entry[:haystacks] ||= records.map { |r| Search.haystack_of(r) }.freeze
457
370
  end
458
371
 
459
372
  # PERF: Memoize folded title and tags per record in @records_cache
460
373
  # to avoid re-folding and array joining on every search_ranked query.
461
374
  def folded_fields_for(type, records)
462
375
  entry = @records_cache[type]
463
- unless entry
464
- return records.map do |r|
465
- [Folding.fold(r["title"]), Folding.fold(Array(r["tags"]).join("\n"))]
466
- end
467
- end
468
-
469
- entry[:folded_fields] ||= records.map do |r|
470
- [Folding.fold(r["title"]), Folding.fold(Array(r["tags"]).join("\n"))].freeze
471
- end.freeze
472
- end
376
+ return records.map { |r| Search.folded_fields_of(r) } unless entry
473
377
 
474
- def haystack_of(record)
475
- Folding.fold("#{record['title']}\n#{record['body']}\n#{Array(record['tags']).join("\n")}")
378
+ entry[:folded_fields] ||= records.map { |r| Search.folded_fields_of(r).freeze }.freeze
476
379
  end
477
380
 
478
381
  def resolve_types(type)
@@ -2,6 +2,7 @@
2
2
 
3
3
  require "json"
4
4
  require_relative "../security/redactor"
5
+ require_relative "../tools/truncator"
5
6
  require_relative "../uris"
6
7
 
7
8
  module Rubik
@@ -117,9 +118,7 @@ module Rubik
117
118
 
118
119
  def clip(text)
119
120
  text = text.to_s.scrub
120
- return text if text.length <= PART_LIMIT
121
-
122
- "#{text.slice(0, PART_LIMIT)}\n... [truncated #{text.length - PART_LIMIT} chars]"
121
+ Rubik::Tools::Truncator.clip(text, PART_LIMIT, separator: "\n")
123
122
  end
124
123
  end
125
124
  end
@@ -3,6 +3,7 @@
3
3
  require "monitor"
4
4
  require_relative "../../concurrency"
5
5
  require_relative "../../events"
6
+ require_relative "../layout"
6
7
 
7
8
  module Rubik
8
9
  module Storage
@@ -103,8 +104,6 @@ module Rubik
103
104
  Recall.recall(@store, query, types: types)
104
105
  end
105
106
 
106
- def auto_digest? = @auto_digest
107
-
108
107
  def touched_topics = @monitor.synchronize { @touched_topics.to_a }
109
108
 
110
109
  # record tool thread'inden, sweep worker'dan koşar — get-then-put
@@ -355,7 +354,7 @@ module Rubik
355
354
  def event_key(payload) = "subagent.#{payload[:storage_id].to_s.empty? ? payload[:id] : payload[:storage_id]}.#{payload[:state]}"
356
355
 
357
356
  def fetch_cfg(key, default)
358
- @config.respond_to?(:fetch) ? @config.fetch(key, default) : default
357
+ Rubik::Storage::Layout.config_get(@config, key, default)
359
358
  end
360
359
  end
361
360
  end
@@ -172,6 +172,28 @@ module Rubik
172
172
  "No matching files found for '#{filter}'.#{hint}"
173
173
  end
174
174
 
175
+ # One home for the traversal-refusal disclosure used by the index
176
+ # filter tools (list_files, grep_search): renders the blocked message
177
+ # with the tool's root as the primary allowed root plus the context
178
+ # index's additional roots, so the honest-disclosure list cannot
179
+ # drift between tools. `context_index` may be nil (index unavailable)
180
+ # or a duck-typed double without additional_roots.
181
+ def self.traversal_blocked_message(path, root_dir, context_index)
182
+ allowed = [{ path: root_dir, primary: true }]
183
+ context_index.additional_roots.each { |r| allowed << { path: r, primary: false } } if context_index.respond_to?(:additional_roots)
184
+ DiagnosticReporter.render_traversal_blocked(path, allowed_roots: allowed)
185
+ end
186
+
187
+ # One home for the fuzzy file-not-found disclosure used by the
188
+ # buffer-bound tools (read_file, replace_file_content): suggests the
189
+ # closest known files by basename match. The respond_to?(:all_files)
190
+ # guard keeps test doubles without the file indexer honest.
191
+ def self.file_not_found_message(buffer_manager, path)
192
+ known_files = buffer_manager.respond_to?(:all_files) ? buffer_manager.all_files : []
193
+ candidates = FuzzyMatcher.best_matches(File.basename(path), known_files.map { |f| File.basename(f) })
194
+ DiagnosticReporter.render_file_not_found(path, candidates: candidates)
195
+ end
196
+
175
197
  def to_h
176
198
  schema = @params_schema
177
199
  if !@allow_additional_properties && schema.is_a?(Hash)
@@ -60,11 +60,7 @@ module Rubik
60
60
  @buffer_manager.read(path)
61
61
  end
62
62
 
63
- unless content
64
- known_files = @buffer_manager.respond_to?(:all_files) ? @buffer_manager.all_files : []
65
- candidates = FuzzyMatcher.best_matches(File.basename(path), known_files.map { |f| File.basename(f) })
66
- return ToolOutput.error(DiagnosticReporter.render_file_not_found(path, candidates: candidates))
67
- end
63
+ return ToolOutput.error(BaseTool.file_not_found_message(@buffer_manager, path)) unless content
68
64
 
69
65
  offset = param(args, :offset, type: :integer)
70
66
  limit = param(args, :limit, type: :integer)
@@ -177,11 +173,7 @@ module Rubik
177
173
  return ToolOutput.error(IndexMessages::INDEX_UNAVAILABLE_MESSAGE) unless idx
178
174
 
179
175
  filter, error = BaseTool.normalize_path_filter(path_filter, @root_dir)
180
- if error
181
- allowed = [{ path: @root_dir, primary: true }]
182
- idx.additional_roots.each { |r| allowed << { path: r, primary: false } } if idx.respond_to?(:additional_roots)
183
- return ToolOutput.error(DiagnosticReporter.render_traversal_blocked(path_filter, allowed_roots: allowed))
184
- end
176
+ return ToolOutput.error(BaseTool.traversal_blocked_message(path_filter, @root_dir, idx)) if error
185
177
 
186
178
  # Tools never scan: an empty index answers honestly instead of
187
179
  # triggering a synchronous full_scan inside the tool call.
@@ -273,11 +265,7 @@ module Rubik
273
265
  return ToolOutput.error("Error: `replacement_content` parameter is required.") if replacement.nil?
274
266
 
275
267
  content = @buffer_manager.read(path)
276
- unless content
277
- known_files = (@buffer_manager.respond_to?(:all_files) ? @buffer_manager.all_files : [])
278
- candidates = FuzzyMatcher.best_matches(File.basename(path), known_files.map { |f| File.basename(f) })
279
- return ToolOutput.error(DiagnosticReporter.render_file_not_found(path, candidates: candidates))
280
- end
268
+ return ToolOutput.error(BaseTool.file_not_found_message(@buffer_manager, path)) unless content
281
269
 
282
270
  has_crlf = content.to_s.include?("\r\n")
283
271
  norm_file = content.to_s.gsub("\r\n", "\n")
@@ -5,6 +5,7 @@ require_relative "../../coeffects"
5
5
  require_relative "../index_messages"
6
6
  require_relative "../output"
7
7
  require_relative "../native_search"
8
+ require_relative "../truncator"
8
9
  require_relative "../diagnostic_reporter"
9
10
 
10
11
  module Rubik
@@ -63,12 +64,7 @@ module Rubik
63
64
  ext_filter = param(args, :extension, type: :stripped_string)
64
65
 
65
66
  path_filter, outside_error = BaseTool.normalize_path_filter(path_filter, @root_dir)
66
- if outside_error
67
- allowed = [{ path: @root_dir, primary: true }]
68
- idx = context_index
69
- idx.additional_roots.each { |r| allowed << { path: r, primary: false } } if idx.respond_to?(:additional_roots)
70
- return ToolOutput.error(DiagnosticReporter.render_traversal_blocked(param(args, :path), allowed_roots: allowed))
71
- end
67
+ return ToolOutput.error(BaseTool.traversal_blocked_message(param(args, :path), @root_dir, context_index)) if outside_error
72
68
 
73
69
  case_sensitive = param(args, :case_sensitive, default: false)
74
70
  max_results = param(args, :max_results, type: :integer, default: 50)
@@ -245,9 +241,7 @@ module Rubik
245
241
  end
246
242
 
247
243
  def sanitize_line_content(content)
248
- return content if content.length <= MAX_LINE_CHARS
249
-
250
- "#{content[0..MAX_LINE_CHARS]}... [line truncated, #{content.length} chars total]"
244
+ Rubik::Tools::Truncator.clip_line(content, MAX_LINE_CHARS)
251
245
  end
252
246
 
253
247
  def collect_disk_matches(matches, file_key, regex, max_results)
@@ -5,6 +5,7 @@ require_relative "../output"
5
5
  require_relative "../../runtime"
6
6
  require_relative "../../runtime/repair_probe"
7
7
  require_relative "../../buffer/apply_contract"
8
+ require_relative "../../storage/layout"
8
9
 
9
10
  module Rubik
10
11
  module Tools
@@ -93,9 +94,9 @@ module Rubik
93
94
  private
94
95
 
95
96
  def auto_apply_mode
96
- return nil unless @shell.respond_to?(:config) && @shell.config.respond_to?(:fetch)
97
+ return nil unless @shell.respond_to?(:config)
97
98
 
98
- @shell.config.fetch("buffer.auto_apply", "manual")
99
+ Rubik::Storage::Layout.config_get(@shell.config, "buffer.auto_apply", "manual")
99
100
  end
100
101
  end
101
102
 
@@ -151,24 +152,14 @@ module Rubik
151
152
 
152
153
  return ToolOutput.error("Target and language_or_type must be provided.") if target.empty? || lang.empty?
153
154
 
154
- # 1. Automatic Probing if proposed_cmd is not specified or auto_probe is requested
155
+ # Phase 1: discovery (automatic probing when no command was provided)
155
156
  if !command_provided?(proposed_cmd) && auto_probe
156
- candidate = case target
157
- when "lsp" then Rubik::Runtime::Discovery.probe_lsp(lang, root_dir: @root_dir)
158
- when "test_runner" then Rubik::Runtime::Discovery.discover_test_runners(root_dir: @root_dir, lang: lang).first
159
- when "linter" then Rubik::Runtime::Discovery.discover_formatters(root_dir: @root_dir, lang: lang).first
160
- when "command" then Rubik::Runtime::Discovery.binary_available?(lang) ? lang : nil
161
- end
157
+ candidate = discover_target(target, lang)
162
158
 
163
159
  if candidate
164
160
  proposed_cmd = candidate
165
161
  else
166
- candidates = case target
167
- when "lsp" then Rubik::Runtime::Discovery.lsp_candidates(lang)
168
- when "test_runner" then Rubik::Runtime::Discovery.test_runner_candidates(lang, root_dir: @root_dir)
169
- when "linter" then Rubik::Runtime::Discovery::FORMATTER_CANDIDATES[lang] || []
170
- else []
171
- end
162
+ candidates = discovery_candidates(target, lang)
172
163
  cand_str = candidates.empty? ? "none" : candidates.join(", ")
173
164
  return ToolOutput.error("Auto-probe failed to discover any installed candidate for #{target} (#{lang}). " \
174
165
  "Candidates checked: [#{cand_str}]. Please provide a specific `proposed_command`.")
@@ -177,15 +168,66 @@ module Rubik
177
168
 
178
169
  return ToolOutput.error("No command provided or discovered for #{target} (#{lang}).") unless command_provided?(proposed_cmd)
179
170
 
180
- # 2. Pre-flight Verification in Isolated Sub-Context (ctx.extend())
171
+ # Phase 2: pre-flight verification in an isolated sub-context (ctx.extend())
181
172
  root_ctx = @runtime_manager&.context || Rubik::Runtime::Context.new
182
- sub_ctx = root_ctx.extend
173
+ verified, error_diagnostic = verify_in_sandbox(target, lang, proposed_cmd, root_ctx,
174
+ probe_args: args["probe_args"] || args[:probe_args])
175
+ return ToolOutput.error("Verification failed for #{target} (#{lang}):\n#{error_diagnostic&.format_for_llm}") unless verified
176
+
177
+ # Phase 3: promotion into a disposable transaction sub-context
178
+ result = promote(target, lang, proposed_cmd, root_ctx)
179
+ return result if result.is_a?(ToolOutput)
180
+
181
+ # Keep one lifetime inverse per repaired key, preserving the original
182
+ # baseline across repeated repairs without retaining every transaction.
183
+ promotion_ctx = result.promotion_ctx
184
+ scope_key = [root_ctx, result.service_key]
185
+ if @repair_scopes.key?(scope_key)
186
+ result.state.released = true
187
+ promotion_ctx.dispose
188
+ else
189
+ @repair_scopes[scope_key] = promotion_ctx
190
+ end
191
+
192
+ if @config.nil? && ["lsp", "test_runner", "linter"].include?(target)
193
+ return "⚠️ Promoted '#{display_command(proposed_cmd)}' for #{target} (#{lang}) — no config is attached, " \
194
+ "so the command is active for this session only and was not saved."
195
+ end
183
196
 
197
+ "✨ Successfully verified and promoted runtime service for #{target} (#{lang}): '#{display_command(proposed_cmd)}'. " \
198
+ "Service is now active in the live context."
199
+ end
200
+
201
+ private
202
+
203
+ # Phase 1: automatic probing of an installed candidate for the target.
204
+ def discover_target(target, lang)
205
+ case target
206
+ when "lsp" then Rubik::Runtime::Discovery.probe_lsp(lang, root_dir: @root_dir)
207
+ when "test_runner" then Rubik::Runtime::Discovery.discover_test_runners(root_dir: @root_dir, lang: lang).first
208
+ when "linter" then Rubik::Runtime::Discovery.discover_formatters(root_dir: @root_dir, lang: lang).first
209
+ when "command" then Rubik::Runtime::Discovery.binary_available?(lang) ? lang : nil
210
+ end
211
+ end
212
+
213
+ # Candidates surfaced in the error message when discovery finds nothing.
214
+ def discovery_candidates(target, lang)
215
+ case target
216
+ when "lsp" then Rubik::Runtime::Discovery.lsp_candidates(lang)
217
+ when "test_runner" then Rubik::Runtime::Discovery.test_runner_candidates(lang, root_dir: @root_dir)
218
+ when "linter" then Rubik::Runtime::Discovery::FORMATTER_CANDIDATES[lang] || []
219
+ else []
220
+ end
221
+ end
222
+
223
+ # Phase 2: pre-flight verification in an isolated sub-context. The probe
224
+ # sub-context is always disposed, even when verification raises.
225
+ def verify_in_sandbox(target, lang, proposed_cmd, root_ctx, probe_args: nil)
226
+ sub_ctx = root_ctx.extend
184
227
  verified = false
185
228
  error_diagnostic = nil
186
-
187
229
  begin
188
- verified, error_diagnostic = verify_binary(target, lang, proposed_cmd, sub_ctx, probe_args: args["probe_args"] || args[:probe_args])
230
+ verified, error_diagnostic = verify_binary(target, lang, proposed_cmd, sub_ctx, probe_args: probe_args)
189
231
  rescue StandardError => e
190
232
  error_diagnostic = Rubik::Runtime::DiagnosticEngine.diagnose(
191
233
  cmd: proposed_cmd,
@@ -195,13 +237,19 @@ module Rubik
195
237
  ensure
196
238
  sub_ctx.dispose
197
239
  end
240
+ [verified, error_diagnostic]
241
+ end
198
242
 
199
- return ToolOutput.error("Verification failed for #{target} (#{lang}):\n#{error_diagnostic&.format_for_llm}") unless verified
200
-
243
+ # Phase 3: apply the promoted command inside a disposable transaction
244
+ # sub-context. Returns a Promotion on success or a ToolOutput error with
245
+ # the rollback report; the `phase` marker distinguishes Promotion from
246
+ # Persistence failures. Rollbacks are named objects (see RollbackState)
247
+ # registered in LIFO order into the promotion sub-context.
248
+ def promote(target, lang, proposed_cmd, root_ctx)
201
249
  # Live changes belong to a disposable transaction. Successful project
202
250
  # persistence is an operator decision and outlives lifecycle cleanup.
203
251
  promotion_ctx = root_ctx.extend
204
- released = false
252
+ state = RollbackState.new
205
253
  @repair_scopes ||= {}
206
254
  cfg_key = { "lsp" => "lsp.servers", "test_runner" => "test.runners",
207
255
  "linter" => "linter.commands" }[target]
@@ -211,61 +259,33 @@ module Rubik
211
259
  previous_services = root_ctx.services
212
260
  phase = "Promotion"
213
261
  begin
214
- promotion_ctx.on_dispose do
215
- next if released
216
-
217
- @repair_scopes.delete([root_ctx, service_key]) if @repair_scopes[[root_ctx, service_key]].equal?(promotion_ctx)
218
- unless root_ctx.disposed?
219
- if previous_services.key?(service_key)
220
- if target == "lsp"
221
- restored = @lsp_manager&.clients&.[](lang)
222
- active = restored && (!restored.respond_to?(:alive?) || restored.alive?) &&
223
- (!restored.respond_to?(:running?) || restored.running?)
224
- if active
225
- root_ctx.provide(service_key, restored)
226
- else
227
- root_ctx.unprovide(service_key)
228
- end
229
- else
230
- root_ctx.provide(service_key, previous_services[service_key])
231
- end
232
- else
233
- root_ctx.unprovide(service_key)
234
- end
235
- end
236
- end
262
+ promotion_ctx.on_dispose(ServiceRollback.new(
263
+ root_ctx: root_ctx, promotion_ctx: promotion_ctx, service_key: service_key,
264
+ previous_services: previous_services, target: target, lang: lang,
265
+ lsp_manager: @lsp_manager, repair_scopes: @repair_scopes, state: state
266
+ ))
237
267
  if cfg_key && @config
238
- promotion_ctx.on_dispose do
239
- next if released
240
-
241
- prev_cmd.nil? ? @config.delete(cfg_key) : @config.set(cfg_key, prev_cmd)
242
- end
268
+ promotion_ctx.on_dispose(ConfigRollback.new(config: @config, cfg_key: cfg_key, prev_cmd: prev_cmd, state: state))
243
269
  @config.set(cfg_key, proposed_cmd)
244
270
  end
245
271
 
246
272
  case target
247
273
  when "lsp"
248
- raise "LSP manager and config are required for live activation" unless @lsp_manager && @config
274
+ raise RepairRuntimeError, "LSP manager and config are required for live activation" unless @lsp_manager && @config
249
275
 
250
276
  had_client = !@lsp_manager.clients[lang].nil?
251
277
  # The manager owns its client table. Restore the old configured
252
278
  # client on rollback; probe clients never enter that table.
253
- promotion_ctx.on_dispose do
254
- next if released
255
-
256
- @lsp_manager.stop_client(lang)
257
- prev_cmd.nil? ? @config.delete(cfg_key) : @config.set(cfg_key, prev_cmd)
258
- if had_client && !root_ctx.disposed?
259
- restored = @lsp_manager.start_client(lang)
260
- raise "Previous LSP client could not be restarted: #{restored}" unless restored[:ok]
261
- end
262
- end
279
+ promotion_ctx.on_dispose(LspClientRollback.new(
280
+ lsp_manager: @lsp_manager, lang: lang, config: @config, cfg_key: cfg_key,
281
+ prev_cmd: prev_cmd, root_ctx: root_ctx, had_client: had_client, state: state
282
+ ))
263
283
  @lsp_manager.stop_client(lang)
264
284
  start_res = @lsp_manager.start_client(lang)
265
- raise "Failed to start LSP server: #{start_res}" unless start_res.is_a?(Hash) && start_res[:ok]
285
+ raise RepairRuntimeError, "Failed to start LSP server: #{start_res}" unless start_res.is_a?(Hash) && start_res[:ok]
266
286
 
267
287
  service = @lsp_manager.clients[lang]
268
- raise "LSP manager reported success without an active client" unless service
288
+ raise RepairRuntimeError, "LSP manager reported success without an active client" unless service
269
289
  when "test_runner", "linter"
270
290
  if @adapter_registry
271
291
  adapter = @adapter_registry.get(lang)
@@ -273,12 +293,11 @@ module Rubik
273
293
  field = target == "test_runner" ? :custom_test_cmd : :custom_format_cmd
274
294
  old_value = adapter.public_send(field)
275
295
  old_config = adapter.config
276
- promotion_ctx.on_dispose do
277
- next if released
278
-
279
- adapter.public_send("#{field}=", old_value)
280
- adapter.config = old_config
281
- end
296
+ promotion_ctx.on_dispose(AdapterFieldRollback.new(adapter: adapter, field: field,
297
+ old_value: old_value, old_config: old_config, state: state))
298
+ # Execution-time gate (TOCTOU closure): the probe ran once but the
299
+ # sink is unguarded; failure raises into the rescue below.
300
+ adapter.send(:validate_custom_command!, proposed_cmd)
282
301
  adapter.config ||= @config
283
302
  adapter.public_send("#{field}=", proposed_cmd)
284
303
  else
@@ -286,9 +305,9 @@ module Rubik
286
305
  options = target == "test_runner" ? { test_cmd: proposed_cmd } : { format_cmd: proposed_cmd }
287
306
  adapter = Rubik::Adapter::GenericAdapter.new(lang, **options, guard: @guard)
288
307
  adapter.config = @config
289
- promotion_ctx.on_dispose do
290
- @adapter_registry.unregister(lang) if !released && @adapter_registry.get(lang).equal?(adapter)
291
- end
308
+ promotion_ctx.on_dispose(AdapterUnregisterRollback.new(
309
+ adapter_registry: @adapter_registry, lang: lang, adapter: adapter, state: state
310
+ ))
292
311
  @adapter_registry.register(lang, adapter)
293
312
  end
294
313
  end
@@ -307,28 +326,9 @@ module Rubik
307
326
  detail = rollback_errors.empty? ? "previous session state restored" : "rollback incomplete: #{rollback_errors}"
308
327
  return ToolOutput.error("#{phase} failed for #{target} (#{lang}): #{e.message}; #{detail}")
309
328
  end
310
-
311
- # Keep one lifetime inverse per repaired key, preserving the original
312
- # baseline across repeated repairs without retaining every transaction.
313
- scope_key = [root_ctx, service_key]
314
- if @repair_scopes.key?(scope_key)
315
- released = true
316
- promotion_ctx.dispose
317
- else
318
- @repair_scopes[scope_key] = promotion_ctx
319
- end
320
-
321
- if @config.nil? && ["lsp", "test_runner", "linter"].include?(target)
322
- return "⚠️ Promoted '#{display_command(proposed_cmd)}' for #{target} (#{lang}) — no config is attached, " \
323
- "so the command is active for this session only and was not saved."
324
- end
325
-
326
- "✨ Successfully verified and promoted runtime service for #{target} (#{lang}): '#{display_command(proposed_cmd)}'. " \
327
- "Service is now active in the live context."
329
+ Promotion.new(promotion_ctx: promotion_ctx, service_key: service_key, state: state)
328
330
  end
329
331
 
330
- private
331
-
332
332
  def verify_binary(target, lang, proposed_cmd, sub_ctx, probe_args: nil)
333
333
  Rubik::Runtime::RepairProbe.new(root_dir: @root_dir, guard: @guard).verify(target, lang, proposed_cmd, sub_ctx, probe_args: probe_args)
334
334
  end
@@ -373,3 +373,7 @@ module Rubik
373
373
  end
374
374
  end
375
375
  end
376
+
377
+ # Named rollback objects for RepairRuntimeTool are kept in a companion file
378
+ # (required after the class definition so it reopens it safely).
379
+ require_relative "../lifecycle_rollbacks"
@@ -112,6 +112,9 @@ module Rubik
112
112
  sealed_ctx = Rubik::Runtime::SynthesizedCommandContext.wrap(ctx, shell: @shell, runtime_manager: @runtime_manager)
113
113
  proc_handler.call(cmd_args, sealed_ctx)
114
114
  else
115
+ # Trust model (issue #398): this raw else-branch serves EXPLICITLY authored 3-arity handlers only — bare bodies are rejected upstream by the callable check, so default saves never land here.
116
+ # A 3-arity handler receives the RAW interactive shell (and its dispatch CommandContext via out_ctx) with `guard`, `config`, `buffer_manager`, etc. reachable — the SealedCoeffects deny-list does NOT apply.
117
+ # That is the operator-trusted bootstrap contract, anchored to the synthesis-gate vocabulary above: the code passed run_synthesis_gate here AND, when persisted, its disk hash is verified against the manifest on load (verify_integrity; RUBIK_TRUST_OVERLAYS=1 is the blanket operator override). Authoring a 3-arity proc is the deliberate escape hatch; 2-arity handlers and bare-body overlay saves are sealed.
115
118
  out_ctx = if ctx
116
119
  ctx
117
120
  elsif @shell.respond_to?(:command_context)