rubik 0.8.1 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. checksums.yaml +4 -4
  2. data/ATTRIBUTION.md +2 -2
  3. data/CHANGELOG.md +207 -43
  4. data/README.md +5 -1
  5. data/bin/rubik +15 -10
  6. data/lib/rubik/adapter/base.rb +19 -0
  7. data/lib/rubik/adapter/generic.rb +0 -14
  8. data/lib/rubik/adapter/node.rb +2 -0
  9. data/lib/rubik/ast/treesitter/zig_walker.rb +15 -2
  10. data/lib/rubik/cli/workspace_trust.rb +17 -0
  11. data/lib/rubik/concurrency/worker.rb +143 -0
  12. data/lib/rubik/concurrency.rb +1 -0
  13. data/lib/rubik/config/deep_ops.rb +17 -0
  14. data/lib/rubik/config/defaults.rb +23 -1
  15. data/lib/rubik/config/schema.rb +0 -1
  16. data/lib/rubik/config/store.rb +14 -0
  17. data/lib/rubik/config.rb +7 -3
  18. data/lib/rubik/context/repo_context_reader.rb +27 -8
  19. data/lib/rubik/events.rb +18 -0
  20. data/lib/rubik/kernel/dispatcher.rb +4 -4
  21. data/lib/rubik/kernel/unit.rb +4 -3
  22. data/lib/rubik/log.rb +2 -1
  23. data/lib/rubik/lsp/client.rb +83 -180
  24. data/lib/rubik/lsp/document_store.rb +209 -0
  25. data/lib/rubik/mcp/client.rb +4 -3
  26. data/lib/rubik/mcp/manager.rb +6 -2
  27. data/lib/rubik/mcp/transport/stdio.rb +51 -9
  28. data/lib/rubik/orchestrator/auto_apply.rb +2 -0
  29. data/lib/rubik/orchestrator/budget_manager.rb +18 -2
  30. data/lib/rubik/orchestrator/goal_ledger/deep_ops.rb +41 -0
  31. data/lib/rubik/orchestrator/goal_ledger/drift.rb +2 -1
  32. data/lib/rubik/orchestrator/goal_ledger/ledger.rb +56 -50
  33. data/lib/rubik/orchestrator/goal_ledger/observation_projection.rb +26 -0
  34. data/lib/rubik/orchestrator/goal_ledger/patch.rb +10 -17
  35. data/lib/rubik/orchestrator/goal_ledger/suspend_lifecycle.rb +9 -41
  36. data/lib/rubik/orchestrator/goal_ledger/validator.rb +6 -20
  37. data/lib/rubik/orchestrator/goal_ledger/verifier.rb +3 -14
  38. data/lib/rubik/orchestrator/goal_ledger/xml_render.rb +21 -14
  39. data/lib/rubik/orchestrator/goal_session.rb +505 -0
  40. data/lib/rubik/orchestrator/goal_state.rb +15 -15
  41. data/lib/rubik/orchestrator/loop.rb +62 -63
  42. data/lib/rubik/orchestrator/lsp_feedback.rb +7 -1
  43. data/lib/rubik/orchestrator/subagent/admission_policy.rb +161 -0
  44. data/lib/rubik/orchestrator/subagent/builtin_types.rb +3 -2
  45. data/lib/rubik/orchestrator/subagent/instance.rb +4 -0
  46. data/lib/rubik/orchestrator/subagent/journal.rb +2 -1
  47. data/lib/rubik/orchestrator/subagent/notices.rb +5 -4
  48. data/lib/rubik/orchestrator/subagent/profile_contract.rb +4 -10
  49. data/lib/rubik/orchestrator/subagent/questioner.rb +21 -6
  50. data/lib/rubik/orchestrator/subagent/run_cycle.rb +22 -1
  51. data/lib/rubik/orchestrator/subagent/scoped_registry.rb +34 -2
  52. data/lib/rubik/orchestrator/subagent/step_runner.rb +1 -1
  53. data/lib/rubik/orchestrator/subagent/teardown.rb +4 -0
  54. data/lib/rubik/orchestrator/subagent/transcript_formatter.rb +2 -1
  55. data/lib/rubik/orchestrator/subagent/type_registry.rb +19 -1
  56. data/lib/rubik/orchestrator/turn_executor/subagent_channel.rb +6 -1
  57. data/lib/rubik/orchestrator/turn_executor/user_channel.rb +6 -1
  58. data/lib/rubik/orchestrator/turn_executor.rb +2 -1
  59. data/lib/rubik/orchestrator.rb +1 -0
  60. data/lib/rubik/platform/path.rb +0 -1
  61. data/lib/rubik/platform.rb +15 -0
  62. data/lib/rubik/plugin/storage.rb +20 -29
  63. data/lib/rubik/prompt/context_builder.rb +24 -18
  64. data/lib/rubik/prompt/context_compactor.rb +31 -8
  65. data/lib/rubik/prompt/conversation_rows.rb +33 -0
  66. data/lib/rubik/prompt/doctrine.rb +4 -2
  67. data/lib/rubik/prompt/emergency_compactor.rb +5 -4
  68. data/lib/rubik/repl/commands/agent_context.rb +1 -1
  69. data/lib/rubik/repl/commands/agent_execution.rb +15 -467
  70. data/lib/rubik/repl/commands/buffer.rb +5 -1
  71. data/lib/rubik/repl/commands/lsp.rb +1 -1
  72. data/lib/rubik/repl/commands/mcp.rb +5 -0
  73. data/lib/rubik/repl/commands/subagents.rb +4 -4
  74. data/lib/rubik/repl/commands/workspace.rb +22 -2
  75. data/lib/rubik/repl/config_wiring.rb +24 -7
  76. data/lib/rubik/repl/input_execution.rb +1 -1
  77. data/lib/rubik/repl/input_loop.rb +1 -1
  78. data/lib/rubik/repl/lifecycle.rb +31 -2
  79. data/lib/rubik/repl/pruner/harness.rb +52 -67
  80. data/lib/rubik/repl/pruner/rules.rb +3 -1
  81. data/lib/rubik/repl/service_catalog.rb +1 -1
  82. data/lib/rubik/repl/synthesized_command_context.rb +3 -0
  83. data/lib/rubik/repl/turn_recorder.rb +5 -4
  84. data/lib/rubik/repl.rb +1 -0
  85. data/lib/rubik/runtime/context.rb +5 -0
  86. data/lib/rubik/runtime/discovery.rb +55 -0
  87. data/lib/rubik/runtime/manifest_store.rb +116 -0
  88. data/lib/rubik/runtime/overlay_storage.rb +300 -218
  89. data/lib/rubik/runtime/repair_probe.rb +20 -2
  90. data/lib/rubik/runtime/sealed_coeffects.rb +58 -0
  91. data/lib/rubik/runtime/synthesized_command_context.rb +80 -0
  92. data/lib/rubik/runtime/synthesized_tool_context.rb +123 -0
  93. data/lib/rubik/runtime/task_manager.rb +7 -2
  94. data/lib/rubik/runtime.rb +3 -0
  95. data/lib/rubik/security/allowlist.rb +167 -0
  96. data/lib/rubik/security/audit_log.rb +72 -0
  97. data/lib/rubik/security/classifier/classifier.rb +24 -8
  98. data/lib/rubik/security/classifier/commands/biome.yaml +49 -0
  99. data/lib/rubik/security/classifier/commands/bun.yaml +91 -0
  100. data/lib/rubik/security/classifier/commands/bundle.yaml +107 -0
  101. data/lib/rubik/security/classifier/commands/clang-format.yaml +21 -0
  102. data/lib/rubik/security/classifier/commands/clang.yaml +37 -0
  103. data/lib/rubik/security/classifier/commands/cmake.yaml +37 -0
  104. data/lib/rubik/security/classifier/commands/ctest.yaml +30 -0
  105. data/lib/rubik/security/classifier/commands/gcc.yaml +36 -0
  106. data/lib/rubik/security/classifier/commands/gem.yaml +104 -0
  107. data/lib/rubik/security/classifier/commands/gofmt.yaml +15 -0
  108. data/lib/rubik/security/classifier/commands/pnpm.yaml +8 -8
  109. data/lib/rubik/security/classifier/commands/python.yaml +18 -1
  110. data/lib/rubik/security/classifier/commands/python3.yaml +18 -1
  111. data/lib/rubik/security/classifier/commands/rake.yaml +60 -0
  112. data/lib/rubik/security/classifier/commands/rspec.yaml +42 -0
  113. data/lib/rubik/security/classifier/commands/rubocop.yaml +38 -0
  114. data/lib/rubik/security/classifier/commands/ruby.yaml +25 -0
  115. data/lib/rubik/security/classifier/commands/rustc.yaml +34 -0
  116. data/lib/rubik/security/classifier/commands/zig.yaml +77 -0
  117. data/lib/rubik/security/classifier/database.rb +12 -1
  118. data/lib/rubik/security/classifier/matcher.rb +17 -2
  119. data/lib/rubik/security/classifier/models.rb +3 -2
  120. data/lib/rubik/security/classifier.rb +5 -0
  121. data/lib/rubik/security/command_gate.rb +567 -0
  122. data/lib/rubik/security/guard.rb +96 -989
  123. data/lib/rubik/security/path_policy.rb +117 -0
  124. data/lib/rubik/security/synthesis_gate.rb +300 -0
  125. data/lib/rubik/security.rb +5 -0
  126. data/lib/rubik/storage/ranking.rb +113 -0
  127. data/lib/rubik/storage/store.rb +2 -92
  128. data/lib/rubik/storage/transcript_indexer.rb +2 -3
  129. data/lib/rubik/storage/vakanuvis/harness.rb +49 -89
  130. data/lib/rubik/tools/base.rb +24 -7
  131. data/lib/rubik/tools/builtins/files.rb +2 -0
  132. data/lib/rubik/tools/builtins/goal_ledger.rb +9 -9
  133. data/lib/rubik/tools/builtins/grep.rb +2 -3
  134. data/lib/rubik/tools/builtins/lifecycle.rb +91 -88
  135. data/lib/rubik/tools/builtins/synthesis.rb +124 -64
  136. data/lib/rubik/tools/builtins/unsynthesize.rb +38 -0
  137. data/lib/rubik/tools/catalog.rb +3 -0
  138. data/lib/rubik/tools/declaration.rb +6 -2
  139. data/lib/rubik/tools/lifecycle_rollbacks.rb +87 -0
  140. data/lib/rubik/tools/native_search.rb +2 -1
  141. data/lib/rubik/tools/preflight_runner.rb +107 -14
  142. data/lib/rubik/tools/registry.rb +2 -0
  143. data/lib/rubik/tools/truncator.rb +25 -0
  144. data/lib/rubik/tools/uri_resolver.rb +3 -1
  145. data/lib/rubik/uris.rb +5 -1
  146. data/lib/rubik/version.rb +1 -1
  147. data/lib/rubik.rb +1 -0
  148. metadata +35 -1
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "json"
3
4
  require "stringio"
4
5
  require "timeout"
5
6
  require_relative "../base"
@@ -40,7 +41,9 @@ module Rubik
40
41
  end
41
42
 
42
43
  def execute(args = {})
43
- name = (args["name"] || args[:name]).to_s.strip.delete_prefix("!")
44
+ # One canonical (downcased) spelling for guard checks, persistence, registration, and the dispose inverse.
45
+ clean_name = (args["name"] || args[:name]).to_s.strip.delete_prefix("!").downcase
46
+ name = clean_name
44
47
  description = (args["description"] || args[:description] || "Custom dynamic command").to_s.strip
45
48
  scope = (args["scope"] || args[:scope] || "session").to_s.downcase.to_sym
46
49
  code = (args["code"] || args[:code]).to_s.strip
@@ -49,7 +52,6 @@ module Rubik
49
52
  return ToolOutput.error("Command name cannot be empty") if name.empty?
50
53
  return ToolOutput.error("Handler code cannot be empty") if code.empty?
51
54
 
52
- clean_name = name.to_s.downcase.delete_prefix("!")
53
55
  previous_meta = nil
54
56
  if @shell
55
57
  previous_meta = @shell.commands[clean_name]
@@ -76,12 +78,10 @@ module Rubik
76
78
  "(e.g. ->(args, ctx) { ... } or ->(args, out, shell) { ... })")
77
79
  end
78
80
 
79
- # 1b. Optional pre-flight execution in an isolated child process
80
- # (AGENTS.md §3.4): verifies the handler actually runs before it is
81
- # persisted or registered. A subprocess guarantees the deadline even
82
- # for C extensions and blocking syscalls that Timeout.timeout cannot
83
- # preempt; output goes to a throwaway StringIO inside the child so
84
- # verification never writes to the user's terminal.
81
+ # 1b. Optional pre-flight in an isolated child process (AGENTS.md §3.4):
82
+ # verifies the handler actually runs before persistence/registration,
83
+ # with a deadline even C extensions and blocking syscalls cannot preempt;
84
+ # output goes to a throwaway StringIO so the terminal is never touched.
85
85
  if test_args
86
86
  preflight = PreflightRunner.run(code, test_args, mode: :command, guard: @guard)
87
87
  return ToolOutput.error("Pre-flight verification failed for command '!#{name}': #{preflight}") if preflight.is_a?(String)
@@ -106,35 +106,29 @@ module Rubik
106
106
  # 3. Register live in REPL shell
107
107
  if @shell
108
108
  @shell.register_command(name, description: "#{description} [#{scope}]", custom: true) do |cmd_args, ctx|
109
- # Arity contract (mirrored by OverlayStorage#eval_command and
110
- # PreflightRunner): 1 → args; 2 → the CommandContext (its
111
- # puts/print/flush delegate to the active capture IO); 3 →
112
- # (args, out, shell) for trusted code needing the raw shell.
113
- # Direct invocation outside dispatch (tests, replay) has no
114
- # ctx: use the shell's factory, or its raw output when held
115
- # shell doubles predate the CommandContext contract. The warn
116
- # keeps a dispatch site forgetting ctx visible instead of
117
- # silently auto-healed.
118
- out_ctx = if ctx
119
- ctx
120
- elsif @shell.respond_to?(:command_context)
121
- warn "[rubik] custom command invoked without a dispatch CommandContext" unless ENV["RUBIK_TEST"]
122
- @shell.command_context
123
- else
124
- @shell.output
125
- end
126
109
  if proc_handler.arity == 1
127
110
  proc_handler.call(cmd_args)
128
111
  elsif proc_handler.arity == 2
129
- proc_handler.call(cmd_args, out_ctx)
112
+ sealed_ctx = Rubik::Runtime::SynthesizedCommandContext.wrap(ctx, shell: @shell, runtime_manager: @runtime_manager)
113
+ proc_handler.call(cmd_args, sealed_ctx)
130
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.
118
+ out_ctx = if ctx
119
+ ctx
120
+ elsif @shell.respond_to?(:command_context)
121
+ warn "[rubik] custom command invoked without a dispatch CommandContext" unless ENV["RUBIK_TEST"]
122
+ @shell.command_context
123
+ else
124
+ @shell.output
125
+ end
131
126
  proc_handler.call(cmd_args, out_ctx.respond_to?(:out) ? out_ctx.out : out_ctx, @shell)
132
127
  end
133
128
  end
134
129
 
135
- # Register inverse in Runtime Context. Sound rollback (AGENTS.md §1.A):
136
- # a hot-updated custom command is restored to its previous handler on
137
- # dispose instead of leaving a hole in the command table.
130
+ # Sound rollback (AGENTS.md §1.A): a hot-updated custom command is
131
+ # restored to its previous handler on dispose, not left as a hole.
138
132
  ctx = @runtime_manager&.context || (@shell.respond_to?(:runtime_manager) ? @shell.runtime_manager&.context : nil)
139
133
  if ctx.respond_to?(:on_dispose) || ctx.respond_to?(:register_disposable)
140
134
  hook = ctx.respond_to?(:on_dispose) ? :on_dispose : :register_disposable
@@ -147,6 +141,8 @@ module Rubik
147
141
  @shell.unregister_command(name)
148
142
  end
149
143
  end
144
+ else
145
+ warn "[Synthesize] no runtime context; dispose inverse not registered for '!#{clean_name}'"
150
146
  end
151
147
  end
152
148
 
@@ -182,13 +178,13 @@ module Rubik
182
178
  "accepts arguments; defaults to an empty object schema `{ type: 'object', properties: {} }` " \
183
179
  "for tools that take no arguments)"
184
180
  },
185
- code: { type: "string", description: "Ruby implementation of tool handler: ->(args) { ... } or class extending Rubik::Tools::BaseTool" },
181
+ code: { type: "string", description: "Ruby implementation of tool handler: ->(args) { ... } or ->(args, ctx) { ... }" },
186
182
  test_args: { type: "object", description: "Optional test arguments to perform pre-flight verification in an isolated sandbox" }
187
183
  },
188
184
  required: ["name", "description", "code"]
189
185
  }
190
186
  )
191
- def initialize(tool_registry = nil, overlay_storage = nil, guard = nil, legacy_runtime_manager = nil, runtime_manager: nil)
187
+ def initialize(tool_registry = nil, overlay_storage = nil, guard = nil, legacy_runtime_manager = nil, runtime_manager: nil, runtime_context: nil)
192
188
  super(DECLARATION)
193
189
  @tool_registry = tool_registry
194
190
  # guard, fallback overlay storage'a da geçilir: bootstrap kabul taraması
@@ -196,6 +192,38 @@ module Rubik
196
192
  @guard = guard || Rubik::Security::Guard.new
197
193
  @overlay_storage = overlay_storage || Rubik::Runtime::OverlayStorage.new(guard: @guard)
198
194
  @runtime_manager = runtime_manager || legacy_runtime_manager
195
+ @runtime_context = runtime_context
196
+ end
197
+
198
+ def rebind_to(ctx)
199
+ resolved_reg = ctx.respond_to?(:get) ? (ctx.get(Rubik::Coeffects::TOOL_REGISTRY) || ctx.get("tool_registry")) : (ctx["tool_registry"] if ctx.respond_to?(:[]))
200
+ # The plane's registry wins even when it is this very instance: a fresh Registry would swap a live toolbelt for an empty one.
201
+ new_registry = if resolved_reg then resolved_reg
202
+ elsif ctx.respond_to?(:provide)
203
+ scoped = Rubik::Tools::Registry.new(coeffect_ctx: ctx)
204
+ ctx.provide(Rubik::Coeffects::TOOL_REGISTRY, scoped)
205
+ scoped
206
+ else Rubik::Tools::Registry.new
207
+ end
208
+
209
+ new_runtime_manager = if ctx.is_a?(Rubik::Runtime::Context) then Struct.new(:context).new(ctx)
210
+ elsif ctx.respond_to?(:context) then ctx
211
+ elsif ctx.respond_to?(:get) && ctx.get("runtime_manager") then ctx.get("runtime_manager")
212
+ else @runtime_manager
213
+ end
214
+
215
+ new_runtime_ctx = if ctx.is_a?(Rubik::Runtime::Context) then ctx
216
+ elsif ctx.respond_to?(:context) && ctx.context.is_a?(Rubik::Runtime::Context) then ctx.context
217
+ else @runtime_context
218
+ end
219
+
220
+ self.class.new(
221
+ new_registry,
222
+ @overlay_storage,
223
+ @guard,
224
+ runtime_manager: new_runtime_manager,
225
+ runtime_context: new_runtime_ctx
226
+ )
199
227
  end
200
228
 
201
229
  def execute(args = {})
@@ -205,7 +233,11 @@ module Rubik
205
233
  risk = (args["risk"] || args[:risk] || "execute").to_s.downcase.to_sym
206
234
  return ToolOutput.error("Invalid risk '#{risk}' — must be one of: read, write, execute.") unless [:read, :write, :execute].include?(risk)
207
235
 
208
- schema = args["params_schema"] || args[:params_schema] || { type: "object", properties: {} }
236
+ raw_schema = args["params_schema"] || args[:params_schema]
237
+ schema_or_error = parse_params_schema(raw_schema)
238
+ return schema_or_error if schema_or_error.is_a?(ToolOutput)
239
+
240
+ schema = schema_or_error
209
241
  code = (args["code"] || args[:code]).to_s.strip
210
242
  test_args = args["test_args"] || args[:test_args]
211
243
 
@@ -238,38 +270,51 @@ module Rubik
238
270
  tool_instance = if evaluated.is_a?(Class) && evaluated < Rubik::Tools::BaseTool
239
271
  evaluated.new
240
272
  elsif evaluated.respond_to?(:call)
273
+ rt_ctx = active_context
241
274
  Class.new(Rubik::Tools::BaseTool) do
242
275
  define_method(:initialize) do
243
276
  super(name: name, description: "#{description} [#{scope}]", risk: risk, params_schema: schema)
244
277
  @handler = evaluated
278
+ @runtime_context = rt_ctx
245
279
  end
246
280
 
247
- define_method(:execute) do |exec_args = {}|
248
- @handler.call(exec_args)
281
+ define_method(:execute) do |exec_args = {}, ctx = nil|
282
+ if @handler.respond_to?(:arity) && @handler.arity.zero?
283
+ @handler.call
284
+ elsif Rubik::Runtime::SynthesizedToolContext.accepts_context?(@handler)
285
+ effective_ctx = ctx || @runtime_context || Rubik::Runtime::Context.new
286
+ sealed_ctx = Rubik::Runtime::SynthesizedToolContext.wrap(effective_ctx)
287
+ @handler.call(exec_args, sealed_ctx)
288
+ else
289
+ @handler.call(exec_args)
290
+ end
249
291
  end
250
292
  end.new
251
293
  else
252
- return ToolOutput.error("Tool code must evaluate to a callable Proc (->(args) { ... }) or a BaseTool subclass.")
294
+ return ToolOutput.error("Tool code must evaluate to a callable Proc (e.g. ->(args) { ... } or ->(args, ctx) { ... }).")
253
295
  end
254
296
 
255
- effective_test_args = test_args || {}
256
- preflight = PreflightRunner.run(code, effective_test_args, mode: :tool, guard: @guard)
257
- return ToolOutput.error("Pre-flight verification failed for tool '#{name}': #{preflight}") if preflight.is_a?(String)
258
-
259
- if preflight == :spawn_failed
260
- # Fallback: in-process Timeout (lambda form via the shared
261
- # dispatch; BaseTool-subclass form needs the full runtime and
262
- # always verifies in-process).
263
- sub_ctx = @runtime_manager&.context.respond_to?(:extend) ? @runtime_manager.context.extend : nil
264
- begin
265
- failure = if evaluated.respond_to?(:call)
266
- PreflightRunner.verify_in_process { PreflightRunner.call_handler(evaluated, effective_test_args, mode: :tool) }
267
- else
268
- PreflightRunner.verify_in_process { tool_instance.execute(effective_test_args) }
269
- end
270
- return ToolOutput.error("Pre-flight verification failed for tool '#{name}': #{failure}") if failure
271
- ensure
272
- sub_ctx&.dispose! if sub_ctx.respond_to?(:dispose!)
297
+ if test_args
298
+ ctx_for_preflight = active_context
299
+ needs_in_process = Rubik::Runtime::SynthesizedToolContext.accepts_context?(evaluated) || evaluated.is_a?(Class)
300
+ preflight = needs_in_process ? :in_process : PreflightRunner.run(code, test_args, mode: :tool, guard: @guard)
301
+ return ToolOutput.error("Pre-flight verification failed for tool '#{name}': #{preflight}") if preflight.is_a?(String)
302
+
303
+ if [:spawn_failed, :in_process].include?(preflight)
304
+ sub_ctx = ctx_for_preflight.respond_to?(:extend) ? ctx_for_preflight.extend : nil
305
+ begin
306
+ failure = if evaluated.respond_to?(:call)
307
+ PreflightRunner.verify_in_process do
308
+ PreflightRunner.call_handler(evaluated, test_args, mode: :tool, context: sub_ctx || ctx_for_preflight)
309
+ end
310
+ else
311
+ PreflightRunner.verify_in_process { tool_instance.execute(test_args) }
312
+ end
313
+ return ToolOutput.error("Pre-flight verification failed for tool '#{name}': #{failure}") if failure
314
+ ensure
315
+ sub_ctx&.dispose! if sub_ctx.respond_to?(:dispose!)
316
+ sub_ctx&.dispose if sub_ctx.respond_to?(:dispose)
317
+ end
273
318
  end
274
319
  end
275
320
  rescue ScriptError, StandardError => e
@@ -290,27 +335,42 @@ module Rubik
290
335
  # Register inverse in Runtime Context. When hot-updating an existing
291
336
  # overlay/MCP/synthesized tool, the inverse restores the previous
292
337
  # instance instead of leaving a hole in the toolbelt.
293
- ctx = @runtime_manager&.context
294
- ctx&.on_dispose do
295
- if previous_tool && @tool_registry.respond_to?(:swap)
296
- @tool_registry.swap(name, previous_tool, origin: previous_origin || :overlay)
297
- else
298
- @tool_registry.unregister(name)
338
+ ctx = active_context
339
+ if ctx.respond_to?(:on_dispose) || ctx.respond_to?(:register_disposable)
340
+ hook = ctx.respond_to?(:on_dispose) ? :on_dispose : :register_disposable
341
+ ctx.send(hook) do
342
+ if previous_tool && @tool_registry.respond_to?(:swap)
343
+ @tool_registry.swap(name, previous_tool, origin: previous_origin || :overlay)
344
+ else
345
+ @tool_registry.unregister(name)
346
+ end
299
347
  end
300
348
  end
301
349
  end
302
350
 
303
- verification_note = if test_args
304
- "Pre-flight verified with provided test_args in an isolated sub-context."
305
- else
306
- "Pre-flight verified with default arguments in an isolated sub-context."
307
- end
351
+ verification_note = test_args ? "Pre-flight verified with provided test_args in an isolated sub-context." : "Pre-flight verification skipped (no test_args provided)."
308
352
  "🎉 Successfully synthesized and registered native tool '#{name}' [scope: #{scope}]. " \
309
353
  "#{verification_note} It is now immediately available in your active toolbelt for function calling."
310
354
  end
311
355
 
312
356
  private
313
357
 
358
+ # Returns a params schema Hash, or a ToolOutput.error describing the problem.
359
+ def parse_params_schema(raw_schema)
360
+ return { type: "object", properties: {} } if raw_schema.nil? || (raw_schema.is_a?(String) && raw_schema.strip.empty?)
361
+ return raw_schema if raw_schema.is_a?(Hash)
362
+
363
+ parsed = JSON.parse(raw_schema.to_s)
364
+ parsed.is_a?(Hash) ? parsed : ToolOutput.error("params_schema must be a valid JSON object schema (got #{parsed.class})")
365
+ rescue JSON::ParserError => e
366
+ ToolOutput.error("Invalid params_schema JSON: #{e.message}")
367
+ end
368
+
369
+ def active_context
370
+ @runtime_context || (@runtime_manager&.context if @runtime_manager.respond_to?(:context)) ||
371
+ (@tool_registry.coeffect_ctx if @tool_registry.respond_to?(:coeffect_ctx))
372
+ end
373
+
314
374
  def clean_binding
315
375
  Object.new.instance_eval { binding }
316
376
  end
@@ -37,6 +37,44 @@ module Rubik
37
37
  @runtime_manager = runtime_manager || legacy_runtime_manager
38
38
  end
39
39
 
40
+ def rebind_to(ctx)
41
+ resolved_reg = if ctx.respond_to?(:get)
42
+ ctx.get(Rubik::Coeffects::TOOL_REGISTRY) || ctx.get("tool_registry")
43
+ elsif ctx.respond_to?(:[])
44
+ ctx["tool_registry"]
45
+ end
46
+
47
+ # The plane's registry wins even when it is this very instance (the
48
+ # ScopedRegistry already provided it): creating a fresh Registry here
49
+ # would swap a live toolbelt for an empty one.
50
+ new_registry = if resolved_reg
51
+ resolved_reg
52
+ elsif ctx.respond_to?(:provide)
53
+ scoped = Rubik::Tools::Registry.new(coeffect_ctx: ctx)
54
+ ctx.provide(Rubik::Coeffects::TOOL_REGISTRY, scoped)
55
+ scoped
56
+ else
57
+ Rubik::Tools::Registry.new
58
+ end
59
+
60
+ new_runtime_manager = if ctx.is_a?(Rubik::Runtime::Context)
61
+ Struct.new(:context).new(ctx)
62
+ elsif ctx.respond_to?(:context)
63
+ ctx
64
+ elsif ctx.respond_to?(:get) && ctx.get("runtime_manager")
65
+ ctx.get("runtime_manager")
66
+ else
67
+ @runtime_manager
68
+ end
69
+
70
+ self.class.new(
71
+ @shell,
72
+ new_registry,
73
+ @overlay_storage,
74
+ runtime_manager: new_runtime_manager
75
+ )
76
+ end
77
+
40
78
  def execute(args = {})
41
79
  name = (args["name"] || args[:name]).to_s.strip.delete_prefix("!")
42
80
  kind = (args["kind"] || args[:kind]).to_s.downcase.to_sym
@@ -52,6 +52,7 @@ module Rubik
52
52
  ORCHESTRATOR_ONLY_TOOLS = DECLARATIONS.select(&:root_only?).map(&:name).sort.freeze
53
53
  BUFFER_BOUND_TOOLS = DECLARATIONS.select(&:buffer_bound?).map(&:name).sort.freeze
54
54
  TERMINAL_TOOLS = DECLARATIONS.select(&:terminal?).map(&:name).sort.freeze
55
+ BUFFER_SYNC_WRITERS = DECLARATIONS.select(&:buffer_sync_writer?).map(&:name).sort.freeze
55
56
 
56
57
  module_function
57
58
 
@@ -84,6 +85,8 @@ module Rubik
84
85
  def terminal_tools = TERMINAL_TOOLS
85
86
 
86
87
  def terminal?(name) = TERMINAL_TOOLS.include?(name.to_s)
88
+
89
+ def buffer_sync_writers = BUFFER_SYNC_WRITERS
87
90
  end
88
91
  end
89
92
  end
@@ -22,12 +22,13 @@ module Rubik
22
22
  :buffer_bound, # bool — instance reads a branch buffer; rebuilt when a plane split rebinds it
23
23
  :root_only, # bool — orchestration-memory writer; never copied into a subagent registry
24
24
  :terminal, # bool — turn completion signal; dispatchers route it before gates/malformed handling
25
+ :buffer_sync_writer, # bool — success lands exactly one file (args['path']) in the buffer; LSP feedback syncs it
25
26
  keyword_init: true
26
27
  ) do
27
28
  def initialize(name:, description:, risk: :read, params_schema: {}, aliases: [],
28
29
  allow_additional_properties: true, archetypes: [], subagent_spawn: false,
29
30
  write_grant: false, maestro_blocked: nil, buffer_bound: false, root_only: false,
30
- terminal: false)
31
+ terminal: false, buffer_sync_writer: false)
31
32
  clean_name = name.to_s
32
33
  # Leading digits are tolerated (not required) for legacy dynamic
33
34
  # tools: synthesis/overlay normalize to lowercase snake but do not
@@ -76,7 +77,8 @@ module Rubik
76
77
  end,
77
78
  buffer_bound: buffer_bound ? true : false,
78
79
  root_only: root_only ? true : false,
79
- terminal: terminal ? true : false
80
+ terminal: terminal ? true : false,
81
+ buffer_sync_writer: buffer_sync_writer ? true : false
80
82
  )
81
83
  freeze
82
84
  end
@@ -98,6 +100,8 @@ module Rubik
98
100
  def root_only? = root_only == true
99
101
 
100
102
  def terminal? = terminal == true
103
+
104
+ def buffer_sync_writer? = buffer_sync_writer == true
101
105
  end
102
106
  end
103
107
  end
@@ -0,0 +1,87 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Named rollback objects for RepairRuntimeTool's promotion transaction
4
+ # (issue #427). Each replaces a former inline `on_dispose` closure, responds
5
+ # to #call and is executed in LIFO order by Context#dispose, keeping the
6
+ # rollback contract explicit and the promotion phase unit-testable.
7
+ module Rubik
8
+ module Tools
9
+ class RepairRuntimeTool
10
+ # Shared flag for the rollbacks of one promotion transaction: when a
11
+ # previous repair scope already owns the lifetime inverses for this key,
12
+ # execute marks the transaction released so these rollbacks stay inert.
13
+ RollbackState = Struct.new(:released)
14
+
15
+ # Result of a successful promotion phase.
16
+ Promotion = Struct.new(:promotion_ctx, :service_key, :state, keyword_init: true)
17
+
18
+ ServiceRollback = Struct.new(:root_ctx, :promotion_ctx, :service_key, :previous_services, :target, :lang,
19
+ :lsp_manager, :repair_scopes, :state, keyword_init: true) do
20
+ def call
21
+ return if state.released
22
+
23
+ repair_scopes.delete([root_ctx, service_key]) if repair_scopes[[root_ctx, service_key]].equal?(promotion_ctx)
24
+ restore_service unless root_ctx.disposed?
25
+ end
26
+
27
+ private
28
+
29
+ def restore_service
30
+ if previous_services.key?(service_key)
31
+ if target == "lsp"
32
+ restored = lsp_manager&.clients&.[](lang)
33
+ active = restored && (!restored.respond_to?(:alive?) || restored.alive?) &&
34
+ (!restored.respond_to?(:running?) || restored.running?)
35
+ if active
36
+ root_ctx.provide(service_key, restored)
37
+ else
38
+ root_ctx.unprovide(service_key)
39
+ end
40
+ else
41
+ root_ctx.provide(service_key, previous_services[service_key])
42
+ end
43
+ else
44
+ root_ctx.unprovide(service_key)
45
+ end
46
+ end
47
+ end
48
+
49
+ ConfigRollback = Struct.new(:config, :cfg_key, :prev_cmd, :state, keyword_init: true) do
50
+ def call
51
+ return if state.released
52
+
53
+ prev_cmd.nil? ? config.delete(cfg_key) : config.set(cfg_key, prev_cmd)
54
+ end
55
+ end
56
+
57
+ LspClientRollback = Struct.new(:lsp_manager, :lang, :config, :cfg_key, :prev_cmd, :root_ctx, :had_client,
58
+ :state, keyword_init: true) do
59
+ def call
60
+ return if state.released
61
+
62
+ lsp_manager.stop_client(lang)
63
+ prev_cmd.nil? ? config.delete(cfg_key) : config.set(cfg_key, prev_cmd)
64
+ return unless had_client && !root_ctx.disposed?
65
+
66
+ restored = lsp_manager.start_client(lang)
67
+ raise "Previous LSP client could not be restarted: #{restored}" unless restored[:ok]
68
+ end
69
+ end
70
+
71
+ AdapterFieldRollback = Struct.new(:adapter, :field, :old_value, :old_config, :state, keyword_init: true) do
72
+ def call
73
+ return if state.released
74
+
75
+ adapter.public_send("#{field}=", old_value)
76
+ adapter.config = old_config
77
+ end
78
+ end
79
+
80
+ AdapterUnregisterRollback = Struct.new(:adapter_registry, :lang, :adapter, :state, keyword_init: true) do
81
+ def call
82
+ adapter_registry.unregister(lang) if !state.released && adapter_registry.get(lang).equal?(adapter)
83
+ end
84
+ end
85
+ end
86
+ end
87
+ end
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "open3"
4
+ require_relative "truncator"
4
5
 
5
6
  begin
6
7
  require "tty/which"
@@ -132,7 +133,7 @@ module Rubik
132
133
  end
133
134
 
134
135
  content = scrub_utf8(match[3])
135
- content = "#{content[0..500]}... [line truncated, #{content.length} chars total]" if content.length > 500
136
+ content = Rubik::Tools::Truncator.clip_line(content, 500) if content.length > 500
136
137
 
137
138
  {
138
139
  file: file.tr("\\", "/").sub(%r{\A\./}, ""),