rubik 0.8.1 → 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 (107) hide show
  1. checksums.yaml +4 -4
  2. data/ATTRIBUTION.md +2 -2
  3. data/CHANGELOG.md +100 -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/unit.rb +4 -3
  15. data/lib/rubik/orchestrator/auto_apply.rb +2 -0
  16. data/lib/rubik/orchestrator/budget_manager.rb +18 -2
  17. data/lib/rubik/orchestrator/goal_ledger/deep_ops.rb +41 -0
  18. data/lib/rubik/orchestrator/goal_ledger/drift.rb +2 -1
  19. data/lib/rubik/orchestrator/goal_ledger/ledger.rb +56 -50
  20. data/lib/rubik/orchestrator/goal_ledger/observation_projection.rb +26 -0
  21. data/lib/rubik/orchestrator/goal_ledger/patch.rb +10 -17
  22. data/lib/rubik/orchestrator/goal_ledger/suspend_lifecycle.rb +9 -41
  23. data/lib/rubik/orchestrator/goal_ledger/validator.rb +6 -20
  24. data/lib/rubik/orchestrator/goal_ledger/verifier.rb +3 -14
  25. data/lib/rubik/orchestrator/goal_ledger/xml_render.rb +21 -14
  26. data/lib/rubik/orchestrator/goal_state.rb +15 -15
  27. data/lib/rubik/orchestrator/loop.rb +62 -63
  28. data/lib/rubik/orchestrator/lsp_feedback.rb +7 -1
  29. data/lib/rubik/orchestrator/subagent/admission_policy.rb +161 -0
  30. data/lib/rubik/orchestrator/subagent/builtin_types.rb +3 -2
  31. data/lib/rubik/orchestrator/subagent/notices.rb +5 -4
  32. data/lib/rubik/orchestrator/subagent/profile_contract.rb +4 -10
  33. data/lib/rubik/orchestrator/subagent/run_cycle.rb +22 -1
  34. data/lib/rubik/orchestrator/subagent/scoped_registry.rb +34 -2
  35. data/lib/rubik/orchestrator/subagent/type_registry.rb +19 -1
  36. data/lib/rubik/orchestrator/turn_executor/subagent_channel.rb +6 -1
  37. data/lib/rubik/orchestrator/turn_executor/user_channel.rb +6 -1
  38. data/lib/rubik/orchestrator/turn_executor.rb +2 -1
  39. data/lib/rubik/platform/path.rb +0 -1
  40. data/lib/rubik/prompt/context_builder.rb +24 -18
  41. data/lib/rubik/prompt/context_compactor.rb +31 -8
  42. data/lib/rubik/prompt/conversation_rows.rb +33 -0
  43. data/lib/rubik/prompt/doctrine.rb +4 -2
  44. data/lib/rubik/prompt/emergency_compactor.rb +5 -4
  45. data/lib/rubik/repl/commands/agent_execution.rb +13 -2
  46. data/lib/rubik/repl/commands/buffer.rb +4 -0
  47. data/lib/rubik/repl/commands/mcp.rb +5 -0
  48. data/lib/rubik/repl/commands/subagents.rb +4 -4
  49. data/lib/rubik/repl/commands/workspace.rb +22 -2
  50. data/lib/rubik/repl/config_wiring.rb +24 -7
  51. data/lib/rubik/repl/input_execution.rb +1 -1
  52. data/lib/rubik/repl/lifecycle.rb +3 -2
  53. data/lib/rubik/repl/pruner/harness.rb +52 -67
  54. data/lib/rubik/repl/pruner/rules.rb +3 -1
  55. data/lib/rubik/repl/service_catalog.rb +1 -1
  56. data/lib/rubik/repl/synthesized_command_context.rb +3 -0
  57. data/lib/rubik/repl/turn_recorder.rb +5 -4
  58. data/lib/rubik/repl.rb +1 -0
  59. data/lib/rubik/runtime/context.rb +5 -0
  60. data/lib/rubik/runtime/discovery.rb +55 -0
  61. data/lib/rubik/runtime/overlay_storage.rb +54 -23
  62. data/lib/rubik/runtime/repair_probe.rb +20 -2
  63. data/lib/rubik/runtime/sealed_coeffects.rb +58 -0
  64. data/lib/rubik/runtime/synthesized_command_context.rb +80 -0
  65. data/lib/rubik/runtime/synthesized_tool_context.rb +123 -0
  66. data/lib/rubik/runtime.rb +2 -0
  67. data/lib/rubik/security/classifier/classifier.rb +16 -8
  68. data/lib/rubik/security/classifier/commands/biome.yaml +49 -0
  69. data/lib/rubik/security/classifier/commands/bun.yaml +91 -0
  70. data/lib/rubik/security/classifier/commands/bundle.yaml +107 -0
  71. data/lib/rubik/security/classifier/commands/clang-format.yaml +21 -0
  72. data/lib/rubik/security/classifier/commands/clang.yaml +37 -0
  73. data/lib/rubik/security/classifier/commands/cmake.yaml +37 -0
  74. data/lib/rubik/security/classifier/commands/ctest.yaml +30 -0
  75. data/lib/rubik/security/classifier/commands/gcc.yaml +36 -0
  76. data/lib/rubik/security/classifier/commands/gem.yaml +104 -0
  77. data/lib/rubik/security/classifier/commands/gofmt.yaml +15 -0
  78. data/lib/rubik/security/classifier/commands/pnpm.yaml +8 -8
  79. data/lib/rubik/security/classifier/commands/python.yaml +18 -1
  80. data/lib/rubik/security/classifier/commands/python3.yaml +18 -1
  81. data/lib/rubik/security/classifier/commands/rake.yaml +60 -0
  82. data/lib/rubik/security/classifier/commands/rspec.yaml +42 -0
  83. data/lib/rubik/security/classifier/commands/rubocop.yaml +38 -0
  84. data/lib/rubik/security/classifier/commands/ruby.yaml +25 -0
  85. data/lib/rubik/security/classifier/commands/rustc.yaml +34 -0
  86. data/lib/rubik/security/classifier/commands/zig.yaml +77 -0
  87. data/lib/rubik/security/classifier/database.rb +12 -1
  88. data/lib/rubik/security/classifier/matcher.rb +17 -2
  89. data/lib/rubik/security/classifier/models.rb +3 -2
  90. data/lib/rubik/security/classifier.rb +5 -0
  91. data/lib/rubik/security/guard.rb +133 -39
  92. data/lib/rubik/storage/vakanuvis/harness.rb +49 -89
  93. data/lib/rubik/tools/base.rb +24 -7
  94. data/lib/rubik/tools/builtins/files.rb +2 -0
  95. data/lib/rubik/tools/builtins/goal_ledger.rb +9 -9
  96. data/lib/rubik/tools/builtins/lifecycle.rb +1 -1
  97. data/lib/rubik/tools/builtins/synthesis.rb +121 -64
  98. data/lib/rubik/tools/builtins/unsynthesize.rb +38 -0
  99. data/lib/rubik/tools/catalog.rb +3 -0
  100. data/lib/rubik/tools/declaration.rb +6 -2
  101. data/lib/rubik/tools/preflight_runner.rb +107 -14
  102. data/lib/rubik/tools/registry.rb +2 -0
  103. data/lib/rubik/tools/uri_resolver.rb +3 -1
  104. data/lib/rubik/uris.rb +5 -1
  105. data/lib/rubik/version.rb +1 -1
  106. data/lib/rubik.rb +1 -0
  107. metadata +25 -1
@@ -77,6 +77,7 @@ module Rubik
77
77
  @subagent_notice_inbox = SubagentNoticeInbox.new
78
78
  @goal_mode = false
79
79
  @goal_wait = nil
80
+ @last_prompt_fingerprint = nil
80
81
  end
81
82
 
82
83
  # §7.2 item 3 (ContinuationManager mold): the notice queue lives in
@@ -95,9 +96,7 @@ module Rubik
95
96
 
96
97
  # The merge policy lives in Prompt::ConversationRows (the row-dialect
97
98
  # single home, shared with the REPL injector and the compaction layer).
98
- def merge_notice_block_into_history!(xml_payload)
99
- Prompt::ConversationRows.append_notice!(@history, xml_payload)
100
- end
99
+ def merge_notice_block_into_history!(xml_payload) = Prompt::ConversationRows.append_notice!(@history, xml_payload)
101
100
 
102
101
  def subagent_notice_inbox = (@subagent_notice_inbox ||= SubagentNoticeInbox.new)
103
102
 
@@ -106,14 +105,8 @@ module Rubik
106
105
  # test doubles — which skip initialize — answer goal_mode? false and
107
106
  # never build the collaborator off a nil @shell_deps.
108
107
  def goal_mode? = @goal_mode == true
109
-
110
- def goal_wait
111
- @goal_wait ||= GoalWait.new(@shell_deps)
112
- end
113
-
114
- def continuation_manager
115
- @continuation_manager ||= ContinuationManager.new(config: @config)
116
- end
108
+ def goal_wait = (@goal_wait ||= GoalWait.new(@shell_deps))
109
+ def continuation_manager = (@continuation_manager ||= ContinuationManager.new(config: @config))
117
110
 
118
111
  # Agent-turn-executor plan: response processing is shared with the
119
112
  # subagent channel through TurnExecutor; Loop supplies the
@@ -121,9 +114,7 @@ module Rubik
121
114
  # initialize: several test doubles construct loops via
122
115
  # Class#allocate + instance_variable_set (build_knob_loop), which
123
116
  # skips initialize.
124
- def turn_executor
125
- @turn_executor ||= TurnExecutor.new(channel: TurnExecutor::UserChannel.new(self))
126
- end
117
+ def turn_executor = (@turn_executor ||= TurnExecutor.new(channel: TurnExecutor::UserChannel.new(self)))
127
118
 
128
119
  def extend_budget(extra_steps) = (@max_steps += extra_steps.to_i)
129
120
 
@@ -150,11 +141,7 @@ module Rubik
150
141
  opts = target_model ? { model: target_model } : {}
151
142
  opts[:tools] = @tool_registry.schemas unless plan_only
152
143
 
153
- mode = if plan_only
154
- :plan
155
- else
156
- goal_mode ? :goal : :default
157
- end
144
+ mode = loop_mode(plan_only, goal_mode)
158
145
 
159
146
  # Prompt view built once at the composition boundary: the
160
147
  # orchestrator resolves coeffects (skills index, type registry)
@@ -165,16 +152,12 @@ module Rubik
165
152
  formatted_task = Rubik::Prompt::ContextBuilder.format_user_task(task_prompt)
166
153
 
167
154
  @history << { role: "system", content: system_prompt }
155
+ @last_prompt_fingerprint = prompt_state_fingerprint(plan_only: plan_only)
168
156
 
169
- # Inject prior dialogue turns if provided
170
- if conversation_history && !conversation_history.empty?
171
- conversation_history.each do |turn|
172
- r = turn[:role] || turn["role"]
173
- c = turn[:content] || turn["content"]
174
- next if r.nil? || c.nil? || c.to_s.strip.empty?
175
-
176
- @history << { role: r.to_s, content: c.to_s }
177
- end
157
+ # Inject prior dialogue turns if provided (sanitized against unauthorized system injection and unescaped pin tags)
158
+ Array(conversation_history).each do |turn|
159
+ sanitized = Prompt::ConversationRows.sanitize_dialogue_turn(turn)
160
+ @history << sanitized if sanitized
178
161
  end
179
162
 
180
163
  Rubik::Storage::Vakanuvis::Orientation.inject_session_start!(@history, @runtime_manager, config: @config)
@@ -200,11 +183,7 @@ module Rubik
200
183
  # appending to @history.last may target a tool result or a
201
184
  # content-less assistant message, which provider formatters then
202
185
  # mangle.
203
- approval = if auto
204
- "Step budget auto-extended (unattended continuation, agent.goal_auto_continue_limit)."
205
- else
206
- "User approved extending step budget by #{extra_steps} steps."
207
- end
186
+ approval = auto ? "Step budget auto-extended (unattended continuation, agent.goal_auto_continue_limit)." : "User approved extending step budget by #{extra_steps} steps."
208
187
  continuation_msg = "<step_budget_extended extra=\"#{extra_steps}\" new_max=\"#{@max_steps}\" " \
209
188
  "current=\"#{@step_count}\" auto=\"#{auto}\" " \
210
189
  "message=\"#{approval} " \
@@ -247,6 +226,7 @@ module Rubik
247
226
  @loop_context = @runtime_manager&.context&.extend
248
227
  begin
249
228
  @history << { role: "system", content: render_system_prompt(mode: :goal, plan_only: false, extra_context: nil) }
229
+ @last_prompt_fingerprint = prompt_state_fingerprint(plan_only: false)
250
230
  @history << { role: "user", content: Rubik::Prompt::ContextBuilder.format_user_task(goal_text) }
251
231
  @history << { role: "user", content: ledger.to_xml }
252
232
  append_resume_marker!(reason: reason, suspended_at: suspended_at, attempt: attempt)
@@ -286,6 +266,12 @@ module Rubik
286
266
 
287
267
  private
288
268
 
269
+ def loop_mode(plan_only, goal)
270
+ return :plan if plan_only
271
+
272
+ goal ? :goal : :default
273
+ end
274
+
289
275
  # run() ile resume_from'un paylaşımlı prompt-view üretimi (candidate 2
290
276
  # Phase 2 sözleşmesi): orchestrator coeffect'leri çözer, prompt
291
277
  # katmanı yalnız render eder. run()'ın eski satır içi gövdesi birebir.
@@ -298,13 +284,35 @@ module Rubik
298
284
  root_dir: @root_dir,
299
285
  extra_context: extra_context)
300
286
  Rubik::Prompt::ContextBuilder.build_system_prompt(
301
- mode: mode,
302
- tool_schemas: plan_only ? [] : @tool_registry.schemas,
303
- native_tools: !plan_only,
304
- services: services
287
+ mode: mode, tool_schemas: plan_only ? [] : @tool_registry.schemas,
288
+ native_tools: !plan_only, services: services
305
289
  )
306
290
  end
307
291
 
292
+ # Lightweight fingerprint of environment factors that affect the rendered system prompt.
293
+ # Preserves prompt caching by avoiding regeneration when state is unchanged.
294
+ def prompt_state_fingerprint(plan_only: false)
295
+ tools = plan_only ? [] : (@tool_registry&.schemas&.map { |s| s[:name] || s["name"] } || [])
296
+ skills = Rubik::Coeffects.get(@runtime_manager&.context, Rubik::Coeffects::SKILL_MANAGER)&.prompt_index
297
+ subagents = resolve_type_registry.list.map { |t| t.respond_to?(:name) ? t.name : t.to_s } if resolve_type_registry.respond_to?(:list)
298
+ dirty = @buffer_manager.dirty_files if @buffer_manager.respond_to?(:dirty_files)
299
+ dirty = dirty.is_a?(Hash) ? dirty.keys : Array(dirty)
300
+ lsp_diags = @lsp_manager.respond_to?(:all_diagnostics) ? @lsp_manager.all_diagnostics.size : 0
301
+ [tools, skills, subagents, dirty, lsp_diags].hash
302
+ end
303
+
304
+ # Dynamically updates @history[0] in-place if tools, skills, subagents, dirty files or LSP
305
+ # change mid-execution. Keeps prompt cache intact on zero-change steps.
306
+ def refresh_system_prompt_if_needed!(mode:, plan_only:, extra_context: nil)
307
+ return unless @history&.first && Prompt::ConversationRows.role_of(@history.first) == "system"
308
+ return if (current_fp = prompt_state_fingerprint(plan_only: plan_only)) == @last_prompt_fingerprint
309
+
310
+ @history.first[Prompt::ConversationRows.content_key_of(@history.first)] = render_system_prompt(mode: mode, plan_only: plan_only, extra_context: extra_context)
311
+ @last_prompt_fingerprint = current_fp
312
+ rescue StandardError => e
313
+ Rubik::Log.warn(:orchestrator, "system prompt refresh failed (#{e.class}: #{e.message}); keeping previous system prompt")
314
+ end
315
+
308
316
  # continue_loop'un opts sözleşmesinin aynısı: model override'ı yok —
309
317
  # resume, koşunun başındaki modeliyle sürer.
310
318
  def resume_request_opts
@@ -336,13 +344,10 @@ module Rubik
336
344
  secs = [(Time.now - suspended_at).to_i, 0].max
337
345
  mm, ss = secs.divmod(60)
338
346
  hh, mm = mm.divmod(60)
339
- if hh.positive?
340
- "#{hh}h #{mm.to_s.rjust(2, '0')}m"
341
- elsif mm.positive?
342
- "#{mm}m #{ss.to_s.rjust(2, '0')}s"
343
- else
344
- "#{ss}s"
345
- end
347
+ return "#{hh}h #{mm.to_s.rjust(2, '0')}m" if hh.positive?
348
+ return "#{mm}m #{ss.to_s.rjust(2, '0')}s" if mm.positive?
349
+
350
+ "#{ss}s"
346
351
  end
347
352
 
348
353
  def restore_resume_counters!(counters)
@@ -357,13 +362,8 @@ module Rubik
357
362
  # (review Öneri 3). Loop keeps thin private delegates with the
358
363
  # original names/signatures so call sites and send()-based tests are
359
364
  # untouched.
360
- def provider_registry_key
361
- provider_resolver.registry_key
362
- end
363
-
364
- def provider_llm_config(key, default)
365
- provider_resolver.llm_config(key, default)
366
- end
365
+ def provider_registry_key = provider_resolver.registry_key
366
+ def provider_llm_config(key, default) = provider_resolver.llm_config(key, default)
367
367
 
368
368
  # Built lazily on first use, NOT in initialize: several test doubles
369
369
  # construct loops via Class#allocate + instance_variable_set
@@ -372,9 +372,7 @@ module Rubik
372
372
  # safe: the provider reference is immutable for the loop's lifetime
373
373
  # and the config object is held by reference (values re-read per
374
374
  # fetch — config reactivity preserved).
375
- def provider_resolver
376
- @provider_resolver ||= ProviderResolver.new(provider: @provider, config: @config)
377
- end
375
+ def provider_resolver = (@provider_resolver ||= ProviderResolver.new(provider: @provider, config: @config))
378
376
 
379
377
  def resolve_type_registry
380
378
  if @runtime_manager&.context.respond_to?(:get)
@@ -400,6 +398,7 @@ module Rubik
400
398
  drain_subagent_notices_into_history!
401
399
  @step_count += 1
402
400
 
401
+ refresh_system_prompt_if_needed!(mode: loop_mode(plan_only, goal_mode?), plan_only: plan_only)
403
402
  warned = @budget_manager.evaluate_step_budget_warning!(warned)
404
403
  verify_goal_ledger! if goal_mode?
405
404
  @budget_manager.evaluate_context_compaction!
@@ -422,7 +421,7 @@ module Rubik
422
421
  return result if result
423
422
  end
424
423
 
425
- { ok: false, error: "Max steps budget exceeded (#{@max_steps})", steps: @step_count, tokens: @total_tokens, loop_instance: self }
424
+ { ok: false, error: "Max steps budget exceeded (#{@max_steps})", reason: :budget_exhausted, steps: @step_count, tokens: @total_tokens, loop_instance: self }
426
425
  end
427
426
 
428
427
  # Goal-ledger adım-baı yenilemesi (goal-ledger planı A): compaction
@@ -435,10 +434,14 @@ module Rubik
435
434
  # execute_steps iterasyonudur, bu yüzden doğrudan hook. Hata
436
435
  # izolasyonu: doğrulama asla akışı bozmaz.
437
436
  def verify_goal_ledger!
438
- Rubik::Orchestrator::GoalLedger::Verifier.at_step_boundary!(self)
437
+ # Coeffect çözümü çağıranındır: Verifier Loop'un iç yüzünü tanımaz.
438
+ ledger = Rubik::Coeffects.get(@runtime_manager&.context, Rubik::Coeffects::GOAL_LEDGER)
439
+ return unless ledger
440
+
441
+ Rubik::Orchestrator::GoalLedger::Verifier.verify!(ledger, trigger: :step, root_dir: @root_dir, config: @config)
439
442
  rescue StandardError => e
440
- # Dürüst kanal (Log.warn): debug_warn ENV-gated no-op'tur — doğrulama
441
- # çöktüğünde drift tespiti sessizce duramaz (sessiz-yutma yasağı).
443
+ # Dürüst kanal (Log.warn): doğrulama çöktüğünde drift tespiti
444
+ # sessizce duramaz (sessiz-yutma yasağı; debug_warn ENV-gated no-op).
442
445
  Rubik::Log.warn(:orchestrator, "goal ledger verification failed (#{e.class}: #{e.message}); step continues unverified")
443
446
  end
444
447
 
@@ -450,11 +453,7 @@ module Rubik
450
453
  end
451
454
 
452
455
  def send_llm_request_with_recovery(opts)
453
- streaming_enabled = if opts.key?(:stream)
454
- opts[:stream] == true
455
- else
456
- provider_llm_config("stream", true) != false
457
- end
456
+ streaming_enabled = opts.key?(:stream) ? (opts[:stream] == true) : (provider_llm_config("stream", true) != false)
458
457
 
459
458
  # Plan 61 D-1/D-3: the wire request must share the compaction math's
460
459
  # assumptions. Ollama needs context_limit (sent as num_ctx) or its
@@ -1,5 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "../tools/catalog"
4
+
3
5
  module Rubik
4
6
  module Orchestrator
5
7
  # Gerçek zamanlı LSP tampon-tanı geri beslemesi (Plan 56 D-5) —
@@ -10,7 +12,11 @@ module Rubik
10
12
  module LspFeedback
11
13
  module_function
12
14
 
13
- WRITER_TOOLS = ["write_file", "replace_file_content"].freeze
15
+ # Writers whose success lands exactly one file at args["path"] in the
16
+ # buffer — declared per tool (buffer_sync_writer:) and projected by
17
+ # Catalog, not the wider write-grant set (apply_buffer is multi-file;
18
+ # run_command/storage carry no path).
19
+ WRITER_TOOLS = Rubik::Tools::Catalog.buffer_sync_writers
14
20
 
15
21
  def refresh(deps:, tool_instance:, tool_args:, tool_result:)
16
22
  return tool_result unless tool_result.status == :ok
@@ -0,0 +1,161 @@
1
+ # frozen_string_literal: true
2
+
3
+ # No require of tools/catalog here: this file is loaded from inside the
4
+ # tools/builtins require chain (via profile_contract), and Catalog must not
5
+ # be re-entered mid-load. Every requiring module (scoped_registry,
6
+ # builtin_types) already requires catalog itself, and all Catalog reads
7
+ # happen at call time.
8
+ module Rubik
9
+ module Orchestrator
10
+ module Subagent
11
+ # Single home for "what does plane P get?": the dynamic-origin vocabulary,
12
+ # the risk ladder, the per-plane admission rule, and the capability labels
13
+ # derived from the same rule. ScopedRegistry stays the executor; the
14
+ # built-in archetypes and ProfileContract delegate here so the filters and
15
+ # the labels the prompt prints cannot drift apart.
16
+ module AdmissionPolicy
17
+ module_function
18
+
19
+ # Dynamic-tool origins: on every plane they answer to the risk ladder,
20
+ # same as unknown future origins — the builtin name rule is builtin-only.
21
+ DYNAMIC_ORIGINS = [:synthesis, :overlay].freeze
22
+ MCP = :mcp
23
+ RISK_LADDER = [:read, :write, :execute].freeze
24
+
25
+ LABEL_FULL_CLONE = "full_clone"
26
+ LABEL_READ_WRITE_TEST = "read_write_test"
27
+ LABEL_READ_EXECUTE = "read_execute"
28
+ LABEL_READ_ONLY = "read_only"
29
+
30
+ # One risk-reading idiom for every consumer. Unknown (missing or
31
+ # unrecognized) risk normalizes to nil, which no ladder admits —
32
+ # admission fails closed everywhere.
33
+ def risk_of(tool)
34
+ tool.respond_to?(:risk) ? tool.risk.to_s.downcase.to_sym : nil
35
+ end
36
+
37
+ # The self archetype is the full-clone plane (its name is reserved, so
38
+ # no custom type can collide with it). Every other arity-1-filtered
39
+ # type lands on the custom plane: its own filter governs builtin names,
40
+ # and this policy governs dynamic and MCP origins on top.
41
+ def plane_for(type_def)
42
+ self_plane?(type_def) ? :self : type_def
43
+ end
44
+
45
+ def self_plane?(type_def)
46
+ type_def.respond_to?(:name) && type_def.name.to_s.downcase.strip == "self"
47
+ end
48
+
49
+ # A malformed plane would otherwise fall into the custom rule and
50
+ # silently admit the full builtin catalog — fail loud instead.
51
+ def allowed?(name, tool, origin, plane:)
52
+ return false if Rubik::Tools::Catalog.orchestrator_only_tools.include?(name.to_s)
53
+ unless plane == :research || plane == :coder || plane == :self ||
54
+ (plane.respond_to?(:tool_filter) && plane.respond_to?(:name))
55
+ raise ArgumentError,
56
+ "unknown admission plane #{plane.inspect}; pass :research, :coder, :self or a subagent type_def"
57
+ end
58
+
59
+ case plane
60
+ when :research then research_admits?(name, tool, origin)
61
+ when :coder then coder_admits?(name, tool, origin)
62
+ when :self then self_admits?(tool, origin)
63
+ else custom_admits?(tool, origin, write_grant?(plane))
64
+ end
65
+ end
66
+
67
+ # Name-level grants formula for custom types over the builtin catalog.
68
+ # The origin/risk gate is not folded in here: the executor applies it
69
+ # through allowed? so one idiom covers every arity-1-filtered plane.
70
+ def custom_tool_filter(grants)
71
+ enabled = grants.dup.freeze
72
+ write_tools = Rubik::Tools::Catalog.write_grant_tools
73
+ spawn_tools = Rubik::Tools::Catalog.spawn_tools
74
+
75
+ lambda do |tool_name|
76
+ next false if write_tools.include?(tool_name) && !enabled.include?("write")
77
+ next false if spawn_tools.include?(tool_name) && !enabled.include?("subagent_spawn")
78
+
79
+ true
80
+ end
81
+ end
82
+
83
+ # Capability label for the plane's admitted toolset, simulated over the
84
+ # builtin catalog with the type's own filter — the same predicate the
85
+ # executor gates runtime admission with.
86
+ def capability_label(type_def)
87
+ return LABEL_FULL_CLONE if self_plane?(type_def)
88
+
89
+ declarations = admitted_builtin_declarations(type_def)
90
+ return LABEL_READ_WRITE_TEST if declarations.any?(&:write_grant?)
91
+ return LABEL_READ_EXECUTE if declarations.any? { |declaration| risk_of(declaration) == :execute }
92
+
93
+ LABEL_READ_ONLY
94
+ end
95
+
96
+ # Builtin-origin tools follow the plane's name rule; every other
97
+ # origin (dynamic or unknown) answers to the risk ladder — a future
98
+ # origin can never ride a builtin name past the risk rules.
99
+ def research_admits?(name, tool, origin)
100
+ return false if origin == MCP
101
+ return Rubik::Tools::Catalog.research_tools.include?(name.to_s) if builtin_origin?(origin)
102
+
103
+ risk_of(tool) == :read
104
+ end
105
+
106
+ def coder_admits?(name, tool, origin)
107
+ return false if origin == MCP
108
+ return Rubik::Tools::Catalog.coder_tools.include?(name.to_s) if builtin_origin?(origin)
109
+
110
+ RISK_LADDER.include?(risk_of(tool))
111
+ end
112
+
113
+ def self_admits?(tool, origin)
114
+ return true if builtin_origin?(origin)
115
+
116
+ RISK_LADDER.include?(risk_of(tool))
117
+ end
118
+
119
+ def custom_admits?(tool, origin, write_grant)
120
+ return true if builtin_origin?(origin)
121
+
122
+ risk = risk_of(tool)
123
+ return false unless RISK_LADDER.include?(risk)
124
+
125
+ risk == :read || write_grant
126
+ end
127
+
128
+ # Only the builtin catalog default-allows. Every real, non-builtin
129
+ # origin — known-dynamic, MCP, or a future one — is ladder-gated so a
130
+ # new origin can never bypass the risk rules. nil origin is the
131
+ # registration idiom's implicit builtin.
132
+ def builtin_origin?(origin)
133
+ origin.nil? || origin == :builtin
134
+ end
135
+
136
+ def write_grant?(type_def)
137
+ return true if type_def.respond_to?(:enable_write_tools) && type_def.enable_write_tools
138
+ return false unless type_def.respond_to?(:grants)
139
+
140
+ Array(type_def.grants).include?("write")
141
+ end
142
+
143
+ def admitted_builtin_declarations(type_def)
144
+ filter = type_def.respond_to?(:tool_filter) ? type_def.tool_filter : nil
145
+ unless filter
146
+ raise ArgumentError,
147
+ "type '#{type_def.name}' carries no tool_filter; the capability label cannot simulate admission"
148
+ end
149
+
150
+ root_only = Rubik::Tools::Catalog.orchestrator_only_tools
151
+ Rubik::Tools::Catalog.names
152
+ .select { |name| !root_only.include?(name) && filter.call(name) }
153
+ .filter_map { |name| Rubik::Tools::Catalog[name] }
154
+ end
155
+
156
+ private_class_method :self_plane?, :research_admits?, :coder_admits?, :self_admits?,
157
+ :custom_admits?, :builtin_origin?, :write_grant?, :admitted_builtin_declarations
158
+ end
159
+ end
160
+ end
161
+ end
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "../../tools/catalog"
4
+ require_relative "admission_policy"
4
5
 
5
6
  module Rubik
6
7
  module Orchestrator
@@ -38,7 +39,7 @@ module Rubik
38
39
  "4. Assumptions & Notes: Concrete limitations or next steps. " \
39
40
  "Do NOT call ask_question for routine uncertainties — infer from codebase context and document assumptions under Assumptions & Notes. " \
40
41
  "If the investigation is fundamentally blocked, ask the maestro with the ask_question tool.",
41
- tool_filter: ->(name) { READ_ONLY_TOOLS.include?(name) },
42
+ tool_filter: ->(name, tool = nil, origin = nil) { AdmissionPolicy.allowed?(name, tool, origin, plane: :research) },
42
43
  enable_write_tools: false, enable_subagent_tools: false
43
44
  ),
44
45
  type_def_class.new(
@@ -67,7 +68,7 @@ module Rubik
67
68
  "Do NOT call ask_question for routine implementation choices or minor ambiguities — make standard engineering assumptions " \
68
69
  "aligned with existing codebase patterns and document them under Assumptions & Notes. " \
69
70
  "If a requirement is fundamentally contradictory, ask the maestro with the ask_question tool.",
70
- tool_filter: ->(name) { CODER_TOOLS.include?(name) },
71
+ tool_filter: ->(name, tool = nil, origin = nil) { AdmissionPolicy.allowed?(name, tool, origin, plane: :coder) },
71
72
  enable_write_tools: true, enable_subagent_tools: false
72
73
  ),
73
74
  type_def_class.new(
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "../../events"
3
4
  require_relative "../../platform"
4
5
  require_relative "budget"
5
6
 
@@ -11,16 +12,16 @@ module Rubik
11
12
  module Notices
12
13
  module_function
13
14
 
14
- # Bus event names
15
- COMPLETED_EVENT = :subagent_completed
15
+ # Bus event names; the cross-layer two read the Rubik::Events leaf.
16
+ COMPLETED_EVENT = Rubik::Events::SUBAGENT_COMPLETED
16
17
  BUDGET_EXHAUSTED_EVENT = :subagent_budget_exhausted
17
18
  COMPACTED_EVENT = :subagent_context_compacted
18
19
  AUTO_APPLY_FAILED_EVENT = :subagent_auto_apply_failed
19
20
  ERROR_PAUSED_EVENT = :subagent_error_paused
20
21
  QUESTION_EVENT = :subagent_question
21
- MESSAGE_EVENT = :subagent_message_to_parent
22
+ MESSAGE_EVENT = Rubik::Events::SUBAGENT_MESSAGE_TO_PARENT
22
23
 
23
- # Bus event name -> normalized notice kind.
24
+ # Bus event name -> normalized notice kind; MESSAGE_EVENT routes elsewhere.
24
25
  EVENTS = {
25
26
  COMPLETED_EVENT => :completed,
26
27
  BUDGET_EXHAUSTED_EVENT => :budget_exhausted,
@@ -2,6 +2,7 @@
2
2
 
3
3
  require "json"
4
4
  require_relative "../../coeffects"
5
+ require_relative "admission_policy"
5
6
 
6
7
  module Rubik
7
8
  module Orchestrator
@@ -78,17 +79,10 @@ module Rubik
78
79
  )
79
80
  end
80
81
 
82
+ # Thin delegate: the grants formula lives in the AdmissionPolicy, so
83
+ # custom-type filters and the plane labels share one home.
81
84
  def tool_filter(grants)
82
- enabled = grants.freeze
83
- write_tools = Rubik::Tools::Catalog.write_grant_tools
84
- spawn_tools = Rubik::Tools::Catalog.spawn_tools
85
-
86
- lambda do |tool_name|
87
- next false if write_tools.include?(tool_name) && !enabled.include?("write")
88
- next false if spawn_tools.include?(tool_name) && !enabled.include?("subagent_spawn")
89
-
90
- true
91
- end
85
+ AdmissionPolicy.custom_tool_filter(grants)
92
86
  end
93
87
 
94
88
  def normalize_text(value, field, errors, allow_symbol: false)
@@ -78,7 +78,28 @@ module Rubik
78
78
  "ask_question tool — it blocks until the maestro answers or times out; ask only when the answer " \
79
79
  "truly changes your work.\n\n" \
80
80
  "Perform your assigned task with high precision and provide a structured synthesis report."
81
- @system_prompt && !@system_prompt.strip.empty? ? "#{base}\n\nCustom Instructions:\n#{@system_prompt}" : base
81
+ effective = @system_prompt && !@system_prompt.strip.empty? ? "#{base}\n\nCustom Instructions:\n#{@system_prompt}" : base
82
+
83
+ if @type_name == "self"
84
+ shell_pref = if @config.respond_to?(:fetch)
85
+ @config.fetch("sandbox.shell", "auto")
86
+ elsif @config.is_a?(Hash)
87
+ @config["sandbox.shell"] || "auto"
88
+ else
89
+ "auto"
90
+ end
91
+ if defined?(Rubik::Sandbox::ShellResolver)
92
+ env_line = Rubik::Sandbox::ShellResolver.environment_line(shell_pref)
93
+ effective = "#{effective}\n\n#{env_line}" if env_line && !env_line.empty?
94
+ end
95
+
96
+ if defined?(Rubik::Prompt::ContextBuilder)
97
+ protocol_xml = Rubik::Prompt::ContextBuilder.build_protocol_xml(@root_dir, config: @config)
98
+ effective = "#{effective}\n\n#{protocol_xml}" if protocol_xml && !protocol_xml.empty?
99
+ end
100
+ end
101
+
102
+ effective
82
103
  end
83
104
  end
84
105
  end
@@ -2,6 +2,7 @@
2
2
 
3
3
  require_relative "../../coeffects"
4
4
  require_relative "../../tools/catalog"
5
+ require_relative "admission_policy"
5
6
 
6
7
  module Rubik
7
8
  module Orchestrator
@@ -23,19 +24,50 @@ module Rubik
23
24
 
24
25
  def build(source_registry:, type_def:, child_ctx:, buffer:, parent_buffer:)
25
26
  return nil unless source_registry
27
+ raise ArgumentError, "ScopedRegistry.build requires a type_def; a nil type_def would grant every tool" unless type_def
26
28
 
27
29
  new_reg = Rubik::Tools::Registry.new(coeffect_ctx: child_ctx)
30
+ child_ctx.provide(Rubik::Coeffects::TOOL_REGISTRY, new_reg) if child_ctx.respond_to?(:provide)
28
31
  filter = type_def.tool_filter
32
+ unless filter
33
+ raise ArgumentError,
34
+ "type '#{type_def.name}' carries no tool_filter; a missing filter would grant every tool in the " \
35
+ "source registry. Set an explicit filter: ProfileContract.tool_filter(grants) for custom types, " \
36
+ "an archetype lambda for built-ins."
37
+ end
29
38
 
30
39
  source_registry.list.each do |tool|
31
40
  next if ROOT_ONLY_TOOLS.include?(tool.name)
32
- next unless filter.nil? || filter.call(tool.name)
33
41
 
34
- new_reg.register(bind_tool_buffer(tool, buffer, ctx: child_ctx, parent_buffer: parent_buffer))
42
+ origin = source_registry.origin(tool.name)
43
+ next unless tool_allowed?(filter, tool, origin, type_def)
44
+
45
+ new_reg.register(
46
+ bind_tool_buffer(tool, buffer, ctx: child_ctx, parent_buffer: parent_buffer),
47
+ origin: origin || :builtin
48
+ )
35
49
  end
36
50
  new_reg
37
51
  end
38
52
 
53
+ # Executor only: multi-arity filters own their whole decision; the
54
+ # shared arity-1 rule (name filter, then origin/risk) is the
55
+ # AdmissionPolicy's to answer.
56
+ def tool_allowed?(filter, tool, origin, type_def)
57
+ unless filter
58
+ raise ArgumentError,
59
+ "tool_allowed? requires a type_def with a tool_filter; a nil filter would grant every tool"
60
+ end
61
+
62
+ if filter.arity != 1
63
+ return filter.call(tool.name, tool, origin) ? true : false
64
+ end
65
+
66
+ return false unless filter.call(tool.name)
67
+
68
+ AdmissionPolicy.allowed?(tool.name, tool, origin, plane: AdmissionPolicy.plane_for(type_def))
69
+ end
70
+
39
71
  # Buffer-bound tools (rebuilt only when a branch buffer splits them
40
72
  # off the parent); everything else is context-rebind territory.
41
73
  # Membership is declared on each tool's Declaration (buffer_bound:)
@@ -34,6 +34,7 @@ module Rubik
34
34
  private :register_builtin
35
35
 
36
36
  def register(type_def, context: nil, replace: false)
37
+ reject_caller_tool_filter(type_def)
37
38
  profile = validate_registered_profile(type_def)
38
39
  apply_profile_contract(type_def, profile)
39
40
  register_dynamic(type_def, context: context || type_def.context || @default_context, replace: replace)
@@ -168,10 +169,27 @@ module Rubik
168
169
  type_def.system_prompt = profile.system_prompt
169
170
  type_def.requires = profile.requires
170
171
  type_def.grants = profile.grants
171
- type_def.tool_filter = ProfileContract.tool_filter(profile.grants)
172
+ type_def.tool_filter = ProfileContract.tool_filter(profile.grants).tap do |filter|
173
+ # Mark the installed filter so re-registering the same def (the
174
+ # registry mutated it) is not mistaken for a caller-provided one.
175
+ type_def.instance_variable_set(:@contract_filter, filter)
176
+ end
172
177
  type_def.enable_write_tools = profile.grants.include?("write")
173
178
  type_def.enable_subagent_tools = profile.grants.include?("subagent_spawn")
174
179
  end
180
+
181
+ # The registry installs the profile-contract filter and never honors
182
+ # a caller-provided one — accepting it (validating its shape, then
183
+ # silently discarding it) would hide a discarded security decision,
184
+ # so it is rejected up front.
185
+ def reject_caller_tool_filter(type_def)
186
+ return unless type_def.tool_filter
187
+ return if type_def.tool_filter.equal?(type_def.instance_variable_get(:@contract_filter))
188
+
189
+ raise ArgumentError,
190
+ "type '#{type_def.name}' declares tool_filter; the registry installs the profile-contract filter " \
191
+ "(ProfileContract.tool_filter(grants)) and never honors a caller filter — express intent via grants."
192
+ end
175
193
  end
176
194
  end
177
195
  end
@@ -23,7 +23,12 @@ module Rubik
23
23
  def tool_registry = @inst.tool_registry
24
24
 
25
25
  def limits
26
- { context_limit: @inst.context_limit, max_output_tokens: @inst.max_output_tokens, config: @inst.config }
26
+ reserved = if @inst.respond_to?(:tool_registry) && @inst.tool_registry&.schemas
27
+ Rubik::Prompt::TokenEstimator.estimate_tool_schemas(@inst.tool_registry.schemas)
28
+ else
29
+ 0
30
+ end
31
+ { context_limit: @inst.context_limit, max_output_tokens: @inst.max_output_tokens, config: @inst.config, reserved_tokens: reserved }
27
32
  end
28
33
 
29
34
  # Subagent policy (ToolCallId doctrine): deterministic