rubik 0.8.0 → 0.9.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 (142) hide show
  1. checksums.yaml +4 -4
  2. data/ATTRIBUTION.md +2 -2
  3. data/CHANGELOG.md +164 -1
  4. data/bin/rubik +15 -10
  5. data/lib/rubik/cli/workspace_trust.rb +1 -0
  6. data/lib/rubik/concurrency/worker.rb +143 -0
  7. data/lib/rubik/concurrency.rb +1 -0
  8. data/lib/rubik/config/deep_ops.rb +17 -0
  9. data/lib/rubik/config/defaults.rb +0 -1
  10. data/lib/rubik/config/schema.rb +0 -1
  11. data/lib/rubik/config.rb +7 -3
  12. data/lib/rubik/context/repo_context_reader.rb +27 -8
  13. data/lib/rubik/events.rb +18 -0
  14. data/lib/rubik/kernel/dispatcher.rb +19 -23
  15. data/lib/rubik/kernel/init.rb +22 -18
  16. data/lib/rubik/kernel/unit.rb +4 -3
  17. data/lib/rubik/orchestrator/auto_apply.rb +2 -0
  18. data/lib/rubik/orchestrator/budget_manager.rb +18 -2
  19. data/lib/rubik/orchestrator/goal_ledger/deep_ops.rb +41 -0
  20. data/lib/rubik/orchestrator/goal_ledger/drift.rb +2 -1
  21. data/lib/rubik/orchestrator/goal_ledger/ledger.rb +59 -59
  22. data/lib/rubik/orchestrator/goal_ledger/observation_projection.rb +29 -9
  23. data/lib/rubik/orchestrator/goal_ledger/patch.rb +10 -17
  24. data/lib/rubik/orchestrator/goal_ledger/suspend_lifecycle.rb +9 -41
  25. data/lib/rubik/orchestrator/goal_ledger/validator.rb +6 -20
  26. data/lib/rubik/orchestrator/goal_ledger/verifier.rb +3 -14
  27. data/lib/rubik/orchestrator/goal_ledger/xml_render.rb +21 -14
  28. data/lib/rubik/orchestrator/goal_state.rb +15 -15
  29. data/lib/rubik/orchestrator/loop.rb +62 -63
  30. data/lib/rubik/orchestrator/lsp_feedback.rb +7 -1
  31. data/lib/rubik/orchestrator/subagent/admission_policy.rb +161 -0
  32. data/lib/rubik/orchestrator/subagent/builtin_types.rb +3 -2
  33. data/lib/rubik/orchestrator/subagent/deferred_spec.rb +51 -2
  34. data/lib/rubik/orchestrator/subagent/dependency.rb +20 -20
  35. data/lib/rubik/orchestrator/subagent/execution_reads.rb +1 -1
  36. data/lib/rubik/orchestrator/subagent/journal.rb +3 -9
  37. data/lib/rubik/orchestrator/subagent/lifecycle.rb +10 -1
  38. data/lib/rubik/orchestrator/subagent/notices.rb +5 -4
  39. data/lib/rubik/orchestrator/subagent/paging.rb +49 -0
  40. data/lib/rubik/orchestrator/subagent/profile_contract.rb +4 -10
  41. data/lib/rubik/orchestrator/subagent/reaper.rb +1 -3
  42. data/lib/rubik/orchestrator/subagent/redeploy_transaction.rb +99 -0
  43. data/lib/rubik/orchestrator/subagent/result_archive.rb +12 -22
  44. data/lib/rubik/orchestrator/subagent/reuse.rb +37 -31
  45. data/lib/rubik/orchestrator/subagent/run_cycle.rb +22 -1
  46. data/lib/rubik/orchestrator/subagent/scoped_registry.rb +34 -2
  47. data/lib/rubik/orchestrator/subagent/spawn_transaction.rb +1 -1
  48. data/lib/rubik/orchestrator/subagent/supervisor.rb +6 -2
  49. data/lib/rubik/orchestrator/subagent/task_ownership.rb +2 -2
  50. data/lib/rubik/orchestrator/subagent/transcript_reader.rb +14 -13
  51. data/lib/rubik/orchestrator/subagent/type_registry.rb +19 -1
  52. data/lib/rubik/orchestrator/turn_executor/subagent_channel.rb +6 -1
  53. data/lib/rubik/orchestrator/turn_executor/user_channel.rb +6 -1
  54. data/lib/rubik/orchestrator/turn_executor.rb +2 -1
  55. data/lib/rubik/platform/path.rb +0 -1
  56. data/lib/rubik/prompt/context_builder.rb +24 -18
  57. data/lib/rubik/prompt/context_compactor.rb +31 -8
  58. data/lib/rubik/prompt/conversation_rows.rb +33 -0
  59. data/lib/rubik/prompt/doctrine.rb +4 -2
  60. data/lib/rubik/prompt/emergency_compactor.rb +5 -4
  61. data/lib/rubik/repl/commands/agent_execution.rb +13 -2
  62. data/lib/rubik/repl/commands/buffer.rb +4 -0
  63. data/lib/rubik/repl/commands/mcp.rb +5 -0
  64. data/lib/rubik/repl/commands/subagents.rb +7 -6
  65. data/lib/rubik/repl/commands/workspace.rb +22 -2
  66. data/lib/rubik/repl/config_wiring.rb +24 -7
  67. data/lib/rubik/repl/input_execution.rb +1 -1
  68. data/lib/rubik/repl/lifecycle.rb +3 -2
  69. data/lib/rubik/repl/pruner/harness.rb +52 -67
  70. data/lib/rubik/repl/pruner/rules.rb +3 -1
  71. data/lib/rubik/repl/pruner/service.rb +4 -9
  72. data/lib/rubik/repl/service_catalog.rb +1 -1
  73. data/lib/rubik/repl/synthesized_command_context.rb +3 -0
  74. data/lib/rubik/repl/turn_recorder.rb +5 -4
  75. data/lib/rubik/repl.rb +1 -0
  76. data/lib/rubik/runtime/context.rb +11 -1
  77. data/lib/rubik/runtime/discovery.rb +55 -0
  78. data/lib/rubik/runtime/fiber.rb +17 -5
  79. data/lib/rubik/runtime/manager.rb +19 -12
  80. data/lib/rubik/runtime/overlay_storage.rb +54 -23
  81. data/lib/rubik/runtime/repair_probe.rb +20 -2
  82. data/lib/rubik/runtime/sealed_coeffects.rb +58 -0
  83. data/lib/rubik/runtime/synthesized_command_context.rb +80 -0
  84. data/lib/rubik/runtime/synthesized_tool_context.rb +123 -0
  85. data/lib/rubik/runtime.rb +2 -0
  86. data/lib/rubik/security/classifier/classifier.rb +16 -8
  87. data/lib/rubik/security/classifier/commands/biome.yaml +49 -0
  88. data/lib/rubik/security/classifier/commands/bun.yaml +91 -0
  89. data/lib/rubik/security/classifier/commands/bundle.yaml +107 -0
  90. data/lib/rubik/security/classifier/commands/clang-format.yaml +21 -0
  91. data/lib/rubik/security/classifier/commands/clang.yaml +37 -0
  92. data/lib/rubik/security/classifier/commands/cmake.yaml +37 -0
  93. data/lib/rubik/security/classifier/commands/ctest.yaml +30 -0
  94. data/lib/rubik/security/classifier/commands/gcc.yaml +36 -0
  95. data/lib/rubik/security/classifier/commands/gem.yaml +104 -0
  96. data/lib/rubik/security/classifier/commands/gofmt.yaml +15 -0
  97. data/lib/rubik/security/classifier/commands/pnpm.yaml +8 -8
  98. data/lib/rubik/security/classifier/commands/python.yaml +18 -1
  99. data/lib/rubik/security/classifier/commands/python3.yaml +18 -1
  100. data/lib/rubik/security/classifier/commands/rake.yaml +60 -0
  101. data/lib/rubik/security/classifier/commands/rspec.yaml +42 -0
  102. data/lib/rubik/security/classifier/commands/rubocop.yaml +38 -0
  103. data/lib/rubik/security/classifier/commands/ruby.yaml +25 -0
  104. data/lib/rubik/security/classifier/commands/rustc.yaml +34 -0
  105. data/lib/rubik/security/classifier/commands/zig.yaml +77 -0
  106. data/lib/rubik/security/classifier/database.rb +12 -1
  107. data/lib/rubik/security/classifier/matcher.rb +17 -2
  108. data/lib/rubik/security/classifier/models.rb +3 -2
  109. data/lib/rubik/security/classifier.rb +5 -0
  110. data/lib/rubik/security/guard.rb +133 -39
  111. data/lib/rubik/storage/layout.rb +14 -3
  112. data/lib/rubik/storage/vakanuvis/harness.rb +49 -89
  113. data/lib/rubik/tools/base.rb +55 -7
  114. data/lib/rubik/tools/builtins/dmesg.rb +1 -1
  115. data/lib/rubik/tools/builtins/exec.rb +1 -2
  116. data/lib/rubik/tools/builtins/files.rb +3 -1
  117. data/lib/rubik/tools/builtins/goal_ledger.rb +10 -10
  118. data/lib/rubik/tools/builtins/grep.rb +2 -2
  119. data/lib/rubik/tools/builtins/interactive.rb +1 -3
  120. data/lib/rubik/tools/builtins/lifecycle.rb +1 -1
  121. data/lib/rubik/tools/builtins/lsp.rb +2 -2
  122. data/lib/rubik/tools/builtins/pruner.rb +1 -1
  123. data/lib/rubik/tools/builtins/runtime.rb +1 -1
  124. data/lib/rubik/tools/builtins/send_message.rb +14 -3
  125. data/lib/rubik/tools/builtins/skill.rb +1 -1
  126. data/lib/rubik/tools/builtins/storage.rb +1 -1
  127. data/lib/rubik/tools/builtins/subagent.rb +2 -1
  128. data/lib/rubik/tools/builtins/subagent_lifecycle.rb +5 -3
  129. data/lib/rubik/tools/builtins/symbols.rb +4 -4
  130. data/lib/rubik/tools/builtins/synthesis.rb +121 -64
  131. data/lib/rubik/tools/builtins/task.rb +1 -1
  132. data/lib/rubik/tools/builtins/unsynthesize.rb +38 -0
  133. data/lib/rubik/tools/builtins/vakanuvis.rb +1 -1
  134. data/lib/rubik/tools/catalog.rb +3 -0
  135. data/lib/rubik/tools/declaration.rb +6 -2
  136. data/lib/rubik/tools/preflight_runner.rb +107 -14
  137. data/lib/rubik/tools/registry.rb +2 -0
  138. data/lib/rubik/tools/uri_resolver.rb +3 -1
  139. data/lib/rubik/uris.rb +5 -1
  140. data/lib/rubik/version.rb +1 -1
  141. data/lib/rubik.rb +1 -0
  142. metadata +27 -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,26 @@ 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
+ out_ctx = if ctx
116
+ ctx
117
+ elsif @shell.respond_to?(:command_context)
118
+ warn "[rubik] custom command invoked without a dispatch CommandContext" unless ENV["RUBIK_TEST"]
119
+ @shell.command_context
120
+ else
121
+ @shell.output
122
+ end
131
123
  proc_handler.call(cmd_args, out_ctx.respond_to?(:out) ? out_ctx.out : out_ctx, @shell)
132
124
  end
133
125
  end
134
126
 
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.
127
+ # Sound rollback (AGENTS.md §1.A): a hot-updated custom command is
128
+ # restored to its previous handler on dispose, not left as a hole.
138
129
  ctx = @runtime_manager&.context || (@shell.respond_to?(:runtime_manager) ? @shell.runtime_manager&.context : nil)
139
130
  if ctx.respond_to?(:on_dispose) || ctx.respond_to?(:register_disposable)
140
131
  hook = ctx.respond_to?(:on_dispose) ? :on_dispose : :register_disposable
@@ -147,6 +138,8 @@ module Rubik
147
138
  @shell.unregister_command(name)
148
139
  end
149
140
  end
141
+ else
142
+ warn "[Synthesize] no runtime context; dispose inverse not registered for '!#{clean_name}'"
150
143
  end
151
144
  end
152
145
 
@@ -182,13 +175,13 @@ module Rubik
182
175
  "accepts arguments; defaults to an empty object schema `{ type: 'object', properties: {} }` " \
183
176
  "for tools that take no arguments)"
184
177
  },
185
- code: { type: "string", description: "Ruby implementation of tool handler: ->(args) { ... } or class extending Rubik::Tools::BaseTool" },
178
+ code: { type: "string", description: "Ruby implementation of tool handler: ->(args) { ... } or ->(args, ctx) { ... }" },
186
179
  test_args: { type: "object", description: "Optional test arguments to perform pre-flight verification in an isolated sandbox" }
187
180
  },
188
181
  required: ["name", "description", "code"]
189
182
  }
190
183
  )
191
- def initialize(tool_registry = nil, overlay_storage = nil, guard = nil, legacy_runtime_manager = nil, runtime_manager: nil)
184
+ def initialize(tool_registry = nil, overlay_storage = nil, guard = nil, legacy_runtime_manager = nil, runtime_manager: nil, runtime_context: nil)
192
185
  super(DECLARATION)
193
186
  @tool_registry = tool_registry
194
187
  # guard, fallback overlay storage'a da geçilir: bootstrap kabul taraması
@@ -196,6 +189,38 @@ module Rubik
196
189
  @guard = guard || Rubik::Security::Guard.new
197
190
  @overlay_storage = overlay_storage || Rubik::Runtime::OverlayStorage.new(guard: @guard)
198
191
  @runtime_manager = runtime_manager || legacy_runtime_manager
192
+ @runtime_context = runtime_context
193
+ end
194
+
195
+ def rebind_to(ctx)
196
+ resolved_reg = ctx.respond_to?(:get) ? (ctx.get(Rubik::Coeffects::TOOL_REGISTRY) || ctx.get("tool_registry")) : (ctx["tool_registry"] if ctx.respond_to?(:[]))
197
+ # The plane's registry wins even when it is this very instance: a fresh Registry would swap a live toolbelt for an empty one.
198
+ new_registry = if resolved_reg then resolved_reg
199
+ elsif ctx.respond_to?(:provide)
200
+ scoped = Rubik::Tools::Registry.new(coeffect_ctx: ctx)
201
+ ctx.provide(Rubik::Coeffects::TOOL_REGISTRY, scoped)
202
+ scoped
203
+ else Rubik::Tools::Registry.new
204
+ end
205
+
206
+ new_runtime_manager = if ctx.is_a?(Rubik::Runtime::Context) then Struct.new(:context).new(ctx)
207
+ elsif ctx.respond_to?(:context) then ctx
208
+ elsif ctx.respond_to?(:get) && ctx.get("runtime_manager") then ctx.get("runtime_manager")
209
+ else @runtime_manager
210
+ end
211
+
212
+ new_runtime_ctx = if ctx.is_a?(Rubik::Runtime::Context) then ctx
213
+ elsif ctx.respond_to?(:context) && ctx.context.is_a?(Rubik::Runtime::Context) then ctx.context
214
+ else @runtime_context
215
+ end
216
+
217
+ self.class.new(
218
+ new_registry,
219
+ @overlay_storage,
220
+ @guard,
221
+ runtime_manager: new_runtime_manager,
222
+ runtime_context: new_runtime_ctx
223
+ )
199
224
  end
200
225
 
201
226
  def execute(args = {})
@@ -205,7 +230,11 @@ module Rubik
205
230
  risk = (args["risk"] || args[:risk] || "execute").to_s.downcase.to_sym
206
231
  return ToolOutput.error("Invalid risk '#{risk}' — must be one of: read, write, execute.") unless [:read, :write, :execute].include?(risk)
207
232
 
208
- schema = args["params_schema"] || args[:params_schema] || { type: "object", properties: {} }
233
+ raw_schema = args["params_schema"] || args[:params_schema]
234
+ schema_or_error = parse_params_schema(raw_schema)
235
+ return schema_or_error if schema_or_error.is_a?(ToolOutput)
236
+
237
+ schema = schema_or_error
209
238
  code = (args["code"] || args[:code]).to_s.strip
210
239
  test_args = args["test_args"] || args[:test_args]
211
240
 
@@ -238,38 +267,51 @@ module Rubik
238
267
  tool_instance = if evaluated.is_a?(Class) && evaluated < Rubik::Tools::BaseTool
239
268
  evaluated.new
240
269
  elsif evaluated.respond_to?(:call)
270
+ rt_ctx = active_context
241
271
  Class.new(Rubik::Tools::BaseTool) do
242
272
  define_method(:initialize) do
243
273
  super(name: name, description: "#{description} [#{scope}]", risk: risk, params_schema: schema)
244
274
  @handler = evaluated
275
+ @runtime_context = rt_ctx
245
276
  end
246
277
 
247
- define_method(:execute) do |exec_args = {}|
248
- @handler.call(exec_args)
278
+ define_method(:execute) do |exec_args = {}, ctx = nil|
279
+ if @handler.respond_to?(:arity) && @handler.arity.zero?
280
+ @handler.call
281
+ elsif Rubik::Runtime::SynthesizedToolContext.accepts_context?(@handler)
282
+ effective_ctx = ctx || @runtime_context || Rubik::Runtime::Context.new
283
+ sealed_ctx = Rubik::Runtime::SynthesizedToolContext.wrap(effective_ctx)
284
+ @handler.call(exec_args, sealed_ctx)
285
+ else
286
+ @handler.call(exec_args)
287
+ end
249
288
  end
250
289
  end.new
251
290
  else
252
- return ToolOutput.error("Tool code must evaluate to a callable Proc (->(args) { ... }) or a BaseTool subclass.")
291
+ return ToolOutput.error("Tool code must evaluate to a callable Proc (e.g. ->(args) { ... } or ->(args, ctx) { ... }).")
253
292
  end
254
293
 
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!)
294
+ if test_args
295
+ ctx_for_preflight = active_context
296
+ needs_in_process = Rubik::Runtime::SynthesizedToolContext.accepts_context?(evaluated) || evaluated.is_a?(Class)
297
+ preflight = needs_in_process ? :in_process : PreflightRunner.run(code, test_args, mode: :tool, guard: @guard)
298
+ return ToolOutput.error("Pre-flight verification failed for tool '#{name}': #{preflight}") if preflight.is_a?(String)
299
+
300
+ if [:spawn_failed, :in_process].include?(preflight)
301
+ sub_ctx = ctx_for_preflight.respond_to?(:extend) ? ctx_for_preflight.extend : nil
302
+ begin
303
+ failure = if evaluated.respond_to?(:call)
304
+ PreflightRunner.verify_in_process do
305
+ PreflightRunner.call_handler(evaluated, test_args, mode: :tool, context: sub_ctx || ctx_for_preflight)
306
+ end
307
+ else
308
+ PreflightRunner.verify_in_process { tool_instance.execute(test_args) }
309
+ end
310
+ return ToolOutput.error("Pre-flight verification failed for tool '#{name}': #{failure}") if failure
311
+ ensure
312
+ sub_ctx&.dispose! if sub_ctx.respond_to?(:dispose!)
313
+ sub_ctx&.dispose if sub_ctx.respond_to?(:dispose)
314
+ end
273
315
  end
274
316
  end
275
317
  rescue ScriptError, StandardError => e
@@ -290,27 +332,42 @@ module Rubik
290
332
  # Register inverse in Runtime Context. When hot-updating an existing
291
333
  # overlay/MCP/synthesized tool, the inverse restores the previous
292
334
  # 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)
335
+ ctx = active_context
336
+ if ctx.respond_to?(:on_dispose) || ctx.respond_to?(:register_disposable)
337
+ hook = ctx.respond_to?(:on_dispose) ? :on_dispose : :register_disposable
338
+ ctx.send(hook) do
339
+ if previous_tool && @tool_registry.respond_to?(:swap)
340
+ @tool_registry.swap(name, previous_tool, origin: previous_origin || :overlay)
341
+ else
342
+ @tool_registry.unregister(name)
343
+ end
299
344
  end
300
345
  end
301
346
  end
302
347
 
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
348
+ 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
349
  "🎉 Successfully synthesized and registered native tool '#{name}' [scope: #{scope}]. " \
309
350
  "#{verification_note} It is now immediately available in your active toolbelt for function calling."
310
351
  end
311
352
 
312
353
  private
313
354
 
355
+ # Returns a params schema Hash, or a ToolOutput.error describing the problem.
356
+ def parse_params_schema(raw_schema)
357
+ return { type: "object", properties: {} } if raw_schema.nil? || (raw_schema.is_a?(String) && raw_schema.strip.empty?)
358
+ return raw_schema if raw_schema.is_a?(Hash)
359
+
360
+ parsed = JSON.parse(raw_schema.to_s)
361
+ parsed.is_a?(Hash) ? parsed : ToolOutput.error("params_schema must be a valid JSON object schema (got #{parsed.class})")
362
+ rescue JSON::ParserError => e
363
+ ToolOutput.error("Invalid params_schema JSON: #{e.message}")
364
+ end
365
+
366
+ def active_context
367
+ @runtime_context || (@runtime_manager&.context if @runtime_manager.respond_to?(:context)) ||
368
+ (@tool_registry.coeffect_ctx if @tool_registry.respond_to?(:coeffect_ctx))
369
+ end
370
+
314
371
  def clean_binding
315
372
  Object.new.instance_eval { binding }
316
373
  end
@@ -72,7 +72,7 @@ module Rubik
72
72
  private
73
73
 
74
74
  def resolve_task_manager
75
- @task_manager || (@runtime_context.respond_to?(:get) ? Rubik::Coeffects.get(@runtime_context, Rubik::Coeffects::TASK_MANAGER) : nil)
75
+ service(:task_manager)
76
76
  end
77
77
 
78
78
  def extract_task_id(args)
@@ -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
@@ -75,7 +75,7 @@ module Rubik
75
75
 
76
76
  def execute(args = {})
77
77
  action = (args["action"] || args[:action] || "recall").to_s
78
- harness = Rubik::Coeffects.resolve(@runtime_context, Rubik::Coeffects::VAKANUIS, @harness)
78
+ harness = service(:vakanuvis, @harness)
79
79
  unless harness
80
80
  return ToolOutput.error("Vakanüvis chronicler is not available: disabled by config " \
81
81
  "(subagents.vakanuvis.enabled=false) or no store wired.")
@@ -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
@@ -6,6 +6,7 @@ require "stringio"
6
6
  require "timeout"
7
7
 
8
8
  require_relative "../security/errors"
9
+ require_relative "../runtime/synthesized_tool_context"
9
10
 
10
11
  module Rubik
11
12
  module Tools
@@ -48,10 +49,33 @@ module Rubik
48
49
  def flush
49
50
  out.flush if out.respond_to?(:flush)
50
51
  end
52
+
53
+ def coeffect(_name)
54
+ nil
55
+ end
51
56
  end
52
57
  case payload["mode"]
53
58
  when "tool"
54
- handler.call(payload["args"])
59
+ tool_ctx = Struct.new(:dummy) do
60
+ def require(_name); nil; end
61
+ def get(_name, default = nil); default; end
62
+ def has?(_name); false; end
63
+ def satisfied?(_deps); true; end
64
+ def coeffect(_name); nil; end
65
+ end.new
66
+ pos_params = handler.respond_to?(:parameters) ? handler.parameters.select { |t, _| [:req, :opt, :rest].include?(t) } : []
67
+ accepts_ctx = if pos_params.empty?
68
+ handler.respond_to?(:arity) && handler.arity == 2
69
+ else
70
+ pos_params.count { |t, _| t == :req } <= 2 && pos_params.size >= 2
71
+ end
72
+ if handler.respond_to?(:arity) && handler.arity == 0
73
+ handler.call
74
+ elsif accepts_ctx
75
+ handler.call(payload["args"], tool_ctx)
76
+ else
77
+ handler.call(payload["args"])
78
+ end
55
79
  else
56
80
  view = command_view.new(StringIO.new)
57
81
  case handler.arity
@@ -60,9 +84,14 @@ module Rubik
60
84
  else handler.call(payload["args"], view.out, nil)
61
85
  end
62
86
  end
63
- STDOUT.puts JSON.dump(ok: true)
64
- rescue StandardError, ScriptError => e
65
- STDOUT.puts JSON.dump(ok: false, error: "#{e.class}: #{e.message}")
87
+ STDOUT.puts "\n" + JSON.dump(ok: true)
88
+ rescue StandardError, ScriptError, SystemExit => e
89
+ # SystemExit must be caught too: a handler that prints a fake
90
+ # {"ok":true} line and then calls exit would otherwise leave the
91
+ # fake as the last output line with a clean exit status — the
92
+ # parent's reverse scan would accept it as the verdict. The
93
+ # genuine failure verdict printed here is the LAST line instead.
94
+ STDOUT.puts "\n" + JSON.dump(ok: false, error: "#{e.class}: #{e.message}")
66
95
  end
67
96
  RUBY
68
97
 
@@ -109,15 +138,37 @@ module Rubik
109
138
  nil
110
139
  rescue Timeout::Error
111
140
  "execution timed out after #{timeout} seconds"
141
+ rescue SystemExit => e
142
+ # Same spoof class as the child rescue above: an in-process handler
143
+ # that prints a fake success and calls exit must not terminate the
144
+ # host verification run as a clean pass.
145
+ "SystemExit raised during verification: #{e.message}"
112
146
  rescue StandardError, ScriptError => e
113
147
  "#{e.class}: #{e.message}"
114
148
  end
115
149
 
116
150
  # Parent-side mirror of the child evaluator's dispatch (see CHILD_SCRIPT).
117
151
  # Keeps the fallback path semantically identical to the subprocess path.
118
- def call_handler(handler, args, mode: :command, shell: nil)
152
+ def call_handler(handler, args, mode: :command, shell: nil, context: nil)
119
153
  if mode == :tool
120
- handler.call(args)
154
+ if handler.respond_to?(:arity) && handler.arity.zero?
155
+ handler.call
156
+ elsif Rubik::Runtime::SynthesizedToolContext.accepts_context?(handler)
157
+ tool_ctx = if context.nil?
158
+ Struct.new(:dummy) do
159
+ def require(_name) = nil
160
+ def get(_name, default = nil) = default
161
+ def has?(_name) = false
162
+ def satisfied?(_deps) = true
163
+ def coeffect(_name) = nil
164
+ end.new
165
+ else
166
+ Rubik::Runtime::SynthesizedToolContext.wrap(context)
167
+ end
168
+ handler.call(args, tool_ctx)
169
+ else
170
+ handler.call(args)
171
+ end
121
172
  else
122
173
  command_view = Struct.new(:out) do
123
174
  def puts(*)
@@ -131,6 +182,10 @@ module Rubik
131
182
  def flush
132
183
  out.flush if out.respond_to?(:flush)
133
184
  end
185
+
186
+ def coeffect(_name)
187
+ nil
188
+ end
134
189
  end
135
190
  view = command_view.new(StringIO.new)
136
191
  case handler.arity
@@ -175,7 +230,11 @@ module Rubik
175
230
  nil
176
231
  end
177
232
  parse_verdict(output)
178
- rescue StandardError
233
+ rescue StandardError => e
234
+ # The spawn→in-process downgrade is a weaker isolation level (the
235
+ # caller re-executes the same code in this process), so the
236
+ # infrastructure failure must never vanish without a trace.
237
+ warn "[Preflight] subprocess verification failed (#{e.class}: #{e.message}); falling back to in-process"
179
238
  kill_child(pid) if defined?(pid) && pid
180
239
  :spawn_failed
181
240
  ensure
@@ -194,15 +253,49 @@ module Rubik
194
253
  end
195
254
 
196
255
  def parse_verdict(output)
197
- line = output.lines.reverse.find { |l| l.start_with?("{") }
198
- return "subprocess produced no verdict" unless line
256
+ verdict = nil
257
+ output.lines.reverse_each do |raw_line|
258
+ line = raw_line.strip
259
+ next unless line.include?('"ok"')
260
+
261
+ # Direct parse for clean lines enclosed in braces
262
+ if line.start_with?("{") && line.end_with?("}")
263
+ begin
264
+ candidate = JSON.parse(line)
265
+ if candidate.is_a?(Hash) && candidate.key?("ok")
266
+ verdict = candidate
267
+ break
268
+ end
269
+ rescue JSON::ParserError
270
+ # Fall through to substring extraction below
271
+ end
272
+ end
273
+
274
+ # In-line substring extraction for chatter sharing the line
275
+ start_idx = line.rindex(/\{\s*"ok"\s*:/)
276
+ end_idx = line.rindex("}")
277
+ next unless start_idx && end_idx && end_idx > start_idx
278
+
279
+ begin
280
+ candidate = JSON.parse(line[start_idx..end_idx])
281
+ if candidate.is_a?(Hash) && candidate.key?("ok")
282
+ verdict = candidate
283
+ break
284
+ end
285
+ rescue JSON::ParserError
286
+ next
287
+ end
288
+ end
289
+
290
+ return "subprocess produced no verdict" unless verdict
199
291
 
200
- verdict = JSON.parse(line)
201
- return nil if verdict["ok"]
292
+ # Strict boolean pin: a forged or malformed verdict like {"ok":"false"}
293
+ # or {"ok":1} is truthy in Ruby and must not read as success. The
294
+ # child only ever emits a real boolean via JSON.dump.
295
+ return nil if verdict["ok"] == true
202
296
 
203
- verdict["error"].to_s
204
- rescue JSON::ParserError
205
- "subprocess produced unreadable output"
297
+ err = verdict["error"].to_s
298
+ err.empty? ? "subprocess execution failed" : err
206
299
  end
207
300
  end
208
301
  end
@@ -8,6 +8,8 @@ require_relative "../coeffects"
8
8
  module Rubik
9
9
  module Tools
10
10
  class Registry
11
+ attr_reader :coeffect_ctx
12
+
11
13
  def initialize(coeffect_ctx: nil)
12
14
  @tools = {}
13
15
  @aliases = {}
@@ -229,7 +229,9 @@ module Rubik
229
229
  def read(uri, ctx:, **_)
230
230
  if Rubik::Uris::GOAL_LEDGER.match?(uri)
231
231
  ledger = Rubik::Coeffects.get(ctx, Rubik::Coeffects::GOAL_LEDGER)
232
- return ledger.to_xml if ledger
232
+ if ledger
233
+ return uri.to_s.downcase.end_with?(".json") ? ledger.to_json : ledger.to_xml
234
+ end
233
235
 
234
236
  return ToolOutput.error("No goal ledger available: no !goal run is active (or goal.ledger.enabled=false). " \
235
237
  "The ledger exists only while a goal loop runs; rubik://goal/state may still " \
data/lib/rubik/uris.rb CHANGED
@@ -25,7 +25,7 @@ module Rubik
25
25
  GOAL_STATE = %r{\Arubik://goal(?:/state)?(?:\.xml)?\z}i
26
26
  # Yapılandırılmış Σ okuma yüzeyi (goal-ledger planı A): /state regexi
27
27
  # /ledger'ı EŞLEMEZ — iki ayrı gramer, tek adapter içinde iç dispatch.
28
- GOAL_LEDGER = %r{\Arubik://goal/ledger(?:\.xml)?\z}i
28
+ GOAL_LEDGER = %r{\Arubik://goal/ledger(?:\.(?:xml|json))?\z}i
29
29
  SUBAGENT_TRANSCRIPT = %r{\Arubik://subagent/([^/]+)/transcript(?:\.jsonl)?(?:#.*)?\z}i
30
30
  # Execution-specific retained result (issue #122): capture 1 = unique
31
31
  # storage id, capture 2 = run sequence (nil = latest retained run).
@@ -87,6 +87,10 @@ module Rubik
87
87
  "#{SCHEME}://#{GOAL}/ledger"
88
88
  end
89
89
 
90
+ def goal_ledger_json
91
+ "#{SCHEME}://#{GOAL}/ledger.json"
92
+ end
93
+
90
94
  def subagent_transcript(storage_id)
91
95
  "#{SCHEME}://#{SUBAGENT}/#{storage_id}/transcript"
92
96
  end
data/lib/rubik/version.rb CHANGED
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Rubik
4
- VERSION = "0.8.0"
4
+ VERSION = "0.9.0"
5
5
  end
data/lib/rubik.rb CHANGED
@@ -5,6 +5,7 @@ require_relative "rubik/log"
5
5
  require_relative "rubik/platform"
6
6
  require_relative "rubik/concurrency"
7
7
  require_relative "rubik/uris"
8
+ require_relative "rubik/events"
8
9
  require_relative "rubik/config"
9
10
  require_relative "rubik/event_bus"
10
11
  require_relative "rubik/repl"