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
@@ -1,12 +1,16 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "monitor"
4
+ require_relative "../../concurrency"
5
+ require_relative "../../events"
4
6
 
5
7
  module Rubik
6
8
  module REPL
7
9
  module Pruner
8
10
  # Düzlem 1 çekirdeği (Vakanüvis::Harness yapısı): tek worker thread
9
- # + sınırlı FIFO. ANLIK GÖRÜNTÜ her zaman ÇAĞIRAN thread'de alınır
11
+ # + sınırlı FIFO (Concurrency::Worker iskeleti: atomik kabul,
12
+ # idempotent kapanış, busy sayımı ve son-çare ağı iskelettedir).
13
+ # ANLIK GÖRÜNTÜ her zaman ÇAĞIRAN thread'de alınır
10
14
  # (:turn_finished abonelik bloğu turn thread'inde koşar; araç/komut
11
15
  # çağrısı da turn thread'indedir) — worker shell durumuna ASLA
12
16
  # dokunmaz; o yalnız brif kurar, doğurur, hasat eder ve planı
@@ -14,10 +18,16 @@ module Rubik
14
18
  # — notice yok, wake yok, yalnız dmesg. Uygulama (pencere takası)
15
19
  # yalnız turn thread'inde, apply_staged_prune_plan! üzerinden.
16
20
  class Harness
17
- STOP = :__pruner_stop__
21
+ include Concurrency::Worker
22
+
23
+ # STOP işareti iskeletin tek ev sahibinde; sabit adı yaşar.
24
+ STOP = Concurrency::Worker::STOP
18
25
  MAX_QUEUE = 16
19
- TURN_EVENT = :turn_finished # TurnRecorder::TURN_EVENT_TARGET ile eş pinli
20
- COMPLETED_EVENT = :subagent_completed
26
+ # Olay adları tek evden okunur: Rubik::Events bağımlılıksız bir
27
+ # yapraktır (uris.rb öncülü) — izolasyon doktrini bozulmadan isimler
28
+ # yayıncı ve abonede aynı kaynaktan düşer.
29
+ TURN_EVENT = Rubik::Events::TURN_FINISHED
30
+ COMPLETED_EVENT = Rubik::Events::SUBAGENT_COMPLETED
21
31
  TYPE_NAME = "pruner"
22
32
  PRUNER_ROLE = "Context Pruner"
23
33
 
@@ -48,32 +58,6 @@ module Rubik
48
58
  self
49
59
  end
50
60
 
51
- def stopped? = @monitor.synchronize { @stopped }
52
-
53
- # Dispose sözleşmesi (vakanüvis): FIFO drain olur (STOP dahil önceki
54
- # olaylar işlenir), thread 2 saniyede durmazsa kill + dürüst dmesg.
55
- def shutdown
56
- @monitor.synchronize { @stopped = true }
57
- @monitor.synchronize { @busy += 1 }
58
- @queue.push(STOP)
59
- @worker&.join(2)
60
- if @worker&.alive?
61
- Pruner.log_via(@dmesg, :warn, "worker did not stop in 2s — killing with #{queue_size} event(s) unprocessed")
62
- @worker.kill
63
- end
64
- @worker = nil
65
- end
66
-
67
- def wait_idle(timeout: 2.0)
68
- deadline = Time.now + timeout
69
- sleep 0.01 while busy? && Time.now < deadline
70
- !busy?
71
- end
72
-
73
- def busy? = @monitor.synchronize { @busy.positive? }
74
-
75
- def queue_size = @queue.size
76
-
77
61
  # ---- talep düzlemi (prune_context aracı / !prune komutu) ----------
78
62
 
79
63
  # Zorunlu budama isteği: LLM asla bekletilmez — deterministik makbuz
@@ -106,6 +90,19 @@ module Rubik
106
90
  bits: @gate.status_bits)
107
91
  end
108
92
 
93
+ # ---- olay giriş kapısı ----------------------------------------------
94
+
95
+ # Atomik kabul (stopped-kontrol + push tek kritik bölümde) iskelette:
96
+ # kapanış yarışındaki olay ya STOP'tan önce düşer ve işlenir ya da
97
+ # reddedilir — işleyeneksiz bir olay busy sayımını sızdıramaz.
98
+ def enqueue_event(kind, payload)
99
+ unless payload.is_a?(Hash)
100
+ Pruner.log_via(@dmesg, :warn, "discarded non-hash #{kind} event (#{payload.class})")
101
+ return false
102
+ end
103
+ super
104
+ end
105
+
109
106
  private
110
107
 
111
108
  def subscribe_events
@@ -123,6 +120,9 @@ module Rubik
123
120
  envelope, = @gate.stage_job(@shell.conversation_history, reason: "turn", forced: false)
124
121
  @gate.drop_job(envelope, why: "harness stopped") if envelope && !enqueue_job(envelope)
125
122
  end
123
+ # A completion refused at teardown drops without gate reconcile —
124
+ # terminal by design: the session is ending, nothing reads the
125
+ # gate afterwards.
126
126
  @event_bus.subscribe(COMPLETED_EVENT, context: @context) { |p| enqueue_event(:completed, p) }
127
127
  end
128
128
 
@@ -130,50 +130,35 @@ module Rubik
130
130
  enqueue_event(:job, { envelope: envelope })
131
131
  end
132
132
 
133
- def enqueue_event(kind, payload)
134
- return false if stopped?
133
+ # ---- Concurrency::Worker iskelet kancaları --------------------------
135
134
 
136
- unless payload.is_a?(Hash)
137
- Pruner.log_via(@dmesg, :warn, "discarded non-hash #{kind} event (#{payload.class})")
138
- return false
139
- end
135
+ def worker_max_queue = MAX_QUEUE
140
136
 
141
- drop_oldest! if @queue.size >= MAX_QUEUE
142
- @monitor.synchronize { @busy += 1 }
143
- @queue.push([kind, payload])
144
- true
145
- end
137
+ def worker_warn(message) = Pruner.log_via(@dmesg, :warn, message)
146
138
 
147
- # Taşma düşürmesi asla STOP'u yutamaz (vakanüvis kuralı); düşen
148
- # işin gate'teki izi uzlaştırılır — :job yer tutucusu temizlenir,
149
- # :completed sicil girdisi silinir (kapı asla "uçuşta" takılı
150
- # kalamaz) ve taşan tamamlanmanın id'si loglanır.
151
- def drop_oldest!
152
- item = @queue.pop(true)
153
- if item == STOP
154
- @queue.push(STOP)
155
- else
156
- @monitor.synchronize { @busy -= 1 }
157
- if item[0] == :job
158
- @gate.drop_job(item[1][:envelope], why: "queue overflow")
159
- elsif item[0] == :completed
160
- @gate.discard_completion(item[1])
161
- end
162
- Pruner.log_via(@dmesg, :warn, "event queue overflow — dropped oldest #{item[0]} event")
139
+ # Taşma düşürmesi gate'in izini uzlaştırır — :job yer tutucusu
140
+ # temizlenir, :completed sicil girdisi silinir (kapı asla "uçuşta"
141
+ # takılı kalamaz) ve taşan tamamlanmanın id'si loglanır.
142
+ def worker_drop_accounted(item)
143
+ if item[0] == :job
144
+ @gate.drop_job(item[1][:envelope], why: "queue overflow")
145
+ elsif item[0] == :completed
146
+ @gate.discard_completion(item[1])
163
147
  end
164
- rescue ThreadError
165
- nil
148
+ Pruner.log_via(@dmesg, :warn, "event queue overflow — dropped oldest #{item[0]} event")
166
149
  end
167
150
 
168
- def run_worker
169
- loop do
170
- kind, payload = @queue.pop
171
- break if kind == STOP
172
-
173
- handle_event(kind, payload)
174
- ensure
175
- @monitor.synchronize { @busy -= 1 }
151
+ def worker_dispatch_failed(kind, payload, error)
152
+ # A lost dispatch must reconcile the gate like an overflow drop —
153
+ # an unreconciled :job placeholder or :completed entry would wedge
154
+ # every later prune behind "already in flight".
155
+ case kind
156
+ when :job
157
+ @gate.drop_job(payload[:envelope], why: "dispatch failed") if payload.is_a?(Hash)
158
+ when :completed
159
+ @gate.discard_completion(payload) if payload.is_a?(Hash)
176
160
  end
161
+ Pruner.log_via(@dmesg, :warn, "pruner worker event dispatch failed (#{error.class}: #{error.message}) — worker continues")
177
162
  end
178
163
 
179
164
  # Pruner'in kendi hatası REPL akışını asla bozmaz — uyarı düşer,
@@ -230,7 +230,9 @@ module Rubik
230
230
  # satırı doğması aynı enjeksiyon sınıfıdır — etiketler özet
231
231
  # içinde asla birebir yaşayamaz.
232
232
  clean = clean.gsub("<user_task>", "&lt;user_task&gt;").gsub("</user_task>", "&lt;/user_task&gt;")
233
- clean = clean.gsub("<goal_ledger ", "&lt;goal_ledger ").gsub("</goal_ledger>", "&lt;/goal_ledger>")
233
+ # Etiket adları gramer tek evinden (ContextCompactor) okunur.
234
+ gtag = Prompt::ContextCompactor::GOAL_LEDGER_TAG
235
+ clean = clean.gsub("<#{gtag} ", "&lt;#{gtag} ").gsub("</#{gtag}>", "&lt;/#{gtag}>")
234
236
  clean_op["text"] = clean
235
237
  end
236
238
  normalized << clean_op
@@ -111,7 +111,7 @@ module Rubik
111
111
  # path in the same session without restarts.
112
112
  DEFINITION.new(
113
113
  name: :guard,
114
- builder: ->(s) { Rubik::Security::Guard.for_config(s[:config]) },
114
+ builder: ->(s) { Rubik::Security::Guard.for_config(s[:config], root_dir: s.root_dir) },
115
115
  provide: Rubik::Coeffects::GUARD
116
116
  ),
117
117
  DEFINITION.new(
@@ -0,0 +1,3 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../runtime/synthesized_command_context"
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "../events"
3
4
  require_relative "../prompt/context_compactor"
4
5
  require_relative "../coeffects"
5
6
 
@@ -13,10 +14,10 @@ module Rubik
13
14
  module TurnRecorder
14
15
  MAX_CONVERSATION_ENTRIES = Rubik::Prompt::ContextCompactor::DEFAULT_MAX_CONVERSATION_ENTRIES
15
16
 
16
- # Vakanüvis kök-turn olay adı — harness'in TURN_EVENT sabitiyle eş
17
- # pinlenir (testler iki taraftan kilitler; isim çelişkisi koşuldan
18
- # önce patlar).
19
- TURN_EVENT_TARGET = :turn_finished
17
+ # Vakanüvis kök-turn olay adı — tek ev Rubik::Events yaprağı; harness
18
+ # sabitleri aynı yapraktan okur, isim çelişkisi tasarım aşamasında
19
+ # imkânsızlaşır.
20
+ TURN_EVENT_TARGET = Rubik::Events::TURN_FINISHED
20
21
 
21
22
  # Plan 61 D-7: sticky routing. Once a conversation has started,
22
23
  # free-text turns keep the established provider/model instead of
data/lib/rubik/repl.rb CHANGED
@@ -6,6 +6,7 @@ require_relative "repl/step_formatter"
6
6
  require_relative "repl/commands"
7
7
  require_relative "repl/terminal_guard"
8
8
  require_relative "repl/pruner"
9
+ require_relative "repl/synthesized_command_context"
9
10
  require_relative "repl/shell"
10
11
 
11
12
  module Rubik
@@ -7,6 +7,11 @@ module Rubik
7
7
  module Runtime
8
8
  class CoeffectMissingError < StandardError; end
9
9
 
10
+ # Raised when a sealed context denies a coeffect lookup by policy.
11
+ # Subclasses CoeffectMissingError so existing rescue clauses keep
12
+ # matching.
13
+ class CoeffectBlockedError < CoeffectMissingError; end
14
+
10
15
  # Raised when a disposed context is asked to create new scope. Unlike a
11
16
  # late inverse (which can run now), there is no meaningful fallback for
12
17
  # extend, so it fails fast (AGENTS.md Fail Fast template).
@@ -175,6 +175,8 @@ module Rubik
175
175
  "node" => "npm test"
176
176
  }.freeze
177
177
 
178
+ SHELL_METACHARACTERS = /[;&|<>`$(){}\[\]\\\n\r]/
179
+
178
180
  class << self
179
181
  def lsp_candidates(lang)
180
182
  LSP_CANDIDATES[lang.to_s.downcase] || []
@@ -322,6 +324,59 @@ module Rubik
322
324
  ext_to_lang[best_ext] || "ruby"
323
325
  end
324
326
 
327
+ # Return all recognized candidate command prefixes for a workspace
328
+ def all_candidate_commands(root_dir: Dir.pwd, config: nil)
329
+ effective_root = root_dir || Dir.pwd
330
+ candidates = []
331
+
332
+ # 1. Detected primary language test runners
333
+ primary_lang = detect_primary_language(effective_root)
334
+ if primary_lang
335
+ candidates.concat(test_runner_candidates(primary_lang, root_dir: effective_root, config: config))
336
+ candidates.concat(FORMATTER_CANDIDATES[primary_lang] || [])
337
+ end
338
+
339
+ # 2. Check all marker rules whose files exist in effective_root
340
+ TEST_RUNNER_MARKERS.each do |lang, rules|
341
+ rules.each do |rule|
342
+ marker_path = File.join(effective_root, rule[:marker])
343
+ if File.exist?(marker_path)
344
+ candidates.concat(rule[:candidates])
345
+ candidates.concat(FORMATTER_CANDIDATES[lang] || [])
346
+ end
347
+ end
348
+ end
349
+
350
+ # 3. Add default runners as fallback
351
+ DEFAULT_TEST_RUNNERS.each_value { |runner| candidates << runner }
352
+
353
+ # 4. Include explicit config overrides if provided
354
+ if config
355
+ ["ruby", "python", "rust", "go", "zig", "c", "typescript", "javascript", "vue", "node"].each do |l|
356
+ cfg_cmd = resolve_config_test_cmd(config, l)
357
+ candidates << cfg_cmd if cfg_cmd && !cfg_cmd.empty?
358
+ end
359
+ end
360
+
361
+ candidates.compact.map(&:strip).reject(&:empty?).uniq
362
+ end
363
+
364
+ # True if cmd_str matches a recognized Discovery candidate for the given root_dir
365
+ def recognized_candidate?(cmd_str, root_dir: Dir.pwd, config: nil)
366
+ return false if cmd_str.nil? || cmd_str.to_s.strip.empty?
367
+ return false if cmd_str.to_s.match?(SHELL_METACHARACTERS)
368
+
369
+ clean_cmd = cmd_str.to_s.strip
370
+ candidates = all_candidate_commands(root_dir: root_dir, config: config)
371
+
372
+ # Check exact match or prefix match on whitespace/argument boundaries
373
+ candidates.any? do |candidate|
374
+ clean_cmd == candidate ||
375
+ clean_cmd.start_with?("#{candidate} ") ||
376
+ clean_cmd.start_with?("#{candidate}\t")
377
+ end
378
+ end
379
+
325
380
  private
326
381
 
327
382
  def resolve_config_test_cmd(config, lang_key)
@@ -7,6 +7,8 @@ require "time"
7
7
  # save_manifest atomik yazımı Platform.atomic_write kullanır; dosyanın tek başına
8
8
  # require edilmesi durumunda da çözümlenebilsin diye açık yüklenir.
9
9
  require_relative "../platform"
10
+ require_relative "synthesized_command_context"
11
+ require_relative "synthesized_tool_context"
10
12
 
11
13
  module Rubik
12
14
  module Runtime
@@ -16,10 +18,12 @@ module Rubik
16
18
  COMMAND_SENTINEL = "# Rubik Custom Command:"
17
19
  TOOL_SENTINEL = "# Rubik Custom Tool:"
18
20
 
19
- def initialize(root_dir: Dir.pwd, home_dir: ENV.fetch("HOME", nil), guard: nil)
21
+ def initialize(root_dir: Dir.pwd, home_dir: ENV.fetch("HOME", nil), guard: nil, runtime_manager: nil, runtime_context: nil)
20
22
  @root_dir = File.expand_path(root_dir)
21
23
  @home_dir = File.expand_path(home_dir || ENV["HOME"] || ".")
22
24
  @guard = guard
25
+ @runtime_manager = runtime_manager
26
+ @runtime_context = runtime_context
23
27
  ensure_directories
24
28
  end
25
29
 
@@ -228,27 +232,39 @@ module Rubik
228
232
  end
229
233
 
230
234
  registered = shell.register_command(cmd_name, description: "#{description} [#{scope}]", custom: true) do |args, ctx|
231
- # Arity contract mirrored from SynthesizeCommandTool: 2-arity
232
- # handlers receive the per-dispatch CommandContext (its IO
233
- # methods delegate to the active capture stream), 3-arity keeps
234
- # the raw shell for trusted persisted code. Direct invocation
235
- # outside dispatch has no ctx: use the shell's factory, or its
236
- # raw output for shell doubles predating the contract. The warn
237
- # keeps a ctx-forgetting dispatch site visible instead of
238
- # silently auto-healed.
239
- out_ctx = if ctx
240
- ctx
241
- elsif shell.respond_to?(:command_context)
242
- warn "[rubik] overlay command invoked without a dispatch CommandContext" unless ENV["RUBIK_TEST"]
243
- shell.command_context
244
- else
245
- shell.output
246
- end
247
235
  if proc_handler.arity == 1
248
236
  proc_handler.call(args)
249
237
  elsif proc_handler.arity == 2
250
- proc_handler.call(args, out_ctx)
238
+ warn "[rubik] overlay command invoked without a dispatch CommandContext" unless ctx || ENV["RUBIK_TEST"]
239
+ sealed_ctx = if ctx.is_a?(Rubik::REPL::SynthesizedCommandContext)
240
+ ctx
241
+ else
242
+ output_io = if ctx.respond_to?(:out)
243
+ ctx.out
244
+ elsif ctx
245
+ ctx
246
+ elsif shell.respond_to?(:output)
247
+ shell.output
248
+ else
249
+ $stdout
250
+ end
251
+ runtime_ctx = if shell.respond_to?(:runtime_manager)
252
+ shell.runtime_manager&.context
253
+ elsif ctx.respond_to?(:runtime_manager)
254
+ ctx.runtime_manager&.context
255
+ end
256
+ Rubik::REPL::SynthesizedCommandContext.new(output: output_io, coeffects: runtime_ctx || {})
257
+ end
258
+ proc_handler.call(args, sealed_ctx)
251
259
  else
260
+ out_ctx = if ctx
261
+ ctx
262
+ elsif shell.respond_to?(:command_context)
263
+ warn "[rubik] overlay command invoked without a dispatch CommandContext" unless ENV["RUBIK_TEST"]
264
+ shell.command_context
265
+ else
266
+ shell.output
267
+ end
252
268
  proc_handler.call(args, out_ctx.respond_to?(:out) ? out_ctx.out : out_ctx, shell)
253
269
  end
254
270
  end
@@ -314,7 +330,7 @@ module Rubik
314
330
  verified_dir_entries(project_tools_dir, :project)
315
331
  end
316
332
 
317
- def load_tools(tool_registry)
333
+ def load_tools(tool_registry, runtime_manager: nil, runtime_context: nil)
318
334
  loaded = []
319
335
  list_tools.each do |t_meta|
320
336
  next if t_meta[:integrity] == :rejected
@@ -324,7 +340,7 @@ module Rubik
324
340
  ensure_contained_path!(file_path, target_dir)
325
341
 
326
342
  code = File.read(t_meta[:path])
327
- tool_inst = eval_tool(t_meta[:name], code, t_meta[:scope])
343
+ tool_inst = eval_tool(t_meta[:name], code, t_meta[:scope], runtime_manager: runtime_manager, runtime_context: runtime_context)
328
344
  if tool_inst
329
345
  tool_registry.register(tool_inst, origin: :overlay)
330
346
  loaded << t_meta[:name]
@@ -337,7 +353,7 @@ module Rubik
337
353
  loaded
338
354
  end
339
355
 
340
- def eval_tool(name, code, scope)
356
+ def eval_tool(name, code, scope, runtime_manager: nil, runtime_context: nil)
341
357
  desc_match = code.match(/# Description:\s*(.*)/)
342
358
  description = desc_match ? desc_match[1].strip : "Custom #{scope} tool"
343
359
 
@@ -346,6 +362,10 @@ module Rubik
346
362
  begin
347
363
  JSON.parse(schema_match[1])
348
364
  rescue JSON::ParserError
365
+ # A malformed schema silently claiming "no arguments"
366
+ # hides real overlay bugs; keep loading (the tool is
367
+ # hash-verified) but say so.
368
+ warn "[rubik] overlay tool '#{name}' has a malformed '# Schema:' header; treating as no-arg schema"
349
369
  {}
350
370
  end
351
371
  else
@@ -364,14 +384,25 @@ module Rubik
364
384
  if evaluated.is_a?(Class) && evaluated < Rubik::Tools::BaseTool
365
385
  evaluated.new
366
386
  elsif evaluated.respond_to?(:call)
387
+ runtime_mgr = runtime_manager || @runtime_manager
388
+ runtime_ctx = runtime_context || @runtime_context || (runtime_mgr&.context if runtime_mgr.respond_to?(:context)) || Rubik::Runtime::Context.new
367
389
  Class.new(Rubik::Tools::BaseTool) do
368
390
  define_method(:initialize) do
369
391
  super(name: name, description: "#{description} [#{scope}]", risk: risk, params_schema: schema)
370
392
  @handler = evaluated
393
+ @runtime_context = runtime_ctx
371
394
  end
372
395
 
373
- define_method(:execute) do |args = {}|
374
- @handler.call(args)
396
+ define_method(:execute) do |args = {}, ctx = nil|
397
+ if @handler.respond_to?(:arity) && @handler.arity.zero?
398
+ @handler.call
399
+ elsif Rubik::Runtime::SynthesizedToolContext.accepts_context?(@handler)
400
+ effective_ctx = ctx || @runtime_context || Rubik::Runtime::Context.new
401
+ sealed_ctx = Rubik::Runtime::SynthesizedToolContext.wrap(effective_ctx)
402
+ @handler.call(args, sealed_ctx)
403
+ else
404
+ @handler.call(args)
405
+ end
375
406
  end
376
407
  end.new
377
408
  end
@@ -11,8 +11,11 @@ module Rubik
11
11
  module Runtime
12
12
  # Functional checks own their resources through the caller's probe context.
13
13
  class RepairProbe
14
- def initialize(root_dir:)
14
+ ALLOWED_PROBE_FLAGS = ["--help", "-h", "help", "--version", "-v", "-V", "version", "--status"].freeze
15
+
16
+ def initialize(root_dir:, guard: nil)
15
17
  @root_dir = root_dir
18
+ @guard = guard
16
19
  end
17
20
 
18
21
  PROBE_TIMEOUT = 5
@@ -26,6 +29,15 @@ module Rubik
26
29
  return probe_failure(proposed_cmd, 127, "Availability check failed: executable not found in PATH")
27
30
  end
28
31
 
32
+ if @guard
33
+ cmd_to_check = proposed_cmd.is_a?(Hash) ? [proposed_cmd[:executable], *Array(proposed_cmd[:args])].join(" ") : proposed_cmd.to_s
34
+ begin
35
+ @guard.verify_command_safety!(cmd_to_check)
36
+ rescue Rubik::Security::BlockedWriteError => e
37
+ return probe_failure(proposed_cmd, 1, "Proposed command blocked by security guard: #{e.message}")
38
+ end
39
+ end
40
+
29
41
  if target == "lsp"
30
42
  client = Rubik::LSP::Client.new(lang, root_dir: @root_dir, server_cmd: proposed_cmd)
31
43
  sub_ctx.on_dispose { client.stop }
@@ -45,8 +57,14 @@ module Rubik
45
57
  end
46
58
 
47
59
  probe_args = ["--help"]
60
+ else
61
+ return probe_failure(proposed_cmd, 1, "probe_args must be a non-empty array of strings") unless probe_args.is_a?(Array) && !probe_args.empty? && probe_args.all?(String)
62
+
63
+ disallowed = probe_args.reject { |arg| ALLOWED_PROBE_FLAGS.include?(arg) }
64
+ if disallowed.any?
65
+ return probe_failure(proposed_cmd, 1, "Disallowed probe_args: only safe diagnostic flags #{ALLOWED_PROBE_FLAGS.inspect} are allowed (got: #{disallowed.inspect})")
66
+ end
48
67
  end
49
- return probe_failure(proposed_cmd, 1, "probe_args must be a non-empty array of strings") unless probe_args.is_a?(Array) && !probe_args.empty? && probe_args.all?(String)
50
68
 
51
69
  argv.concat(probe_args)
52
70
  # Array-form spawn never interprets shell operators. File-backed output
@@ -0,0 +1,58 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../coeffects"
4
+ require_relative "../log"
5
+
6
+ module Rubik
7
+ module Runtime
8
+ # Shared capability gate for sealed execution contexts (synthesized tools
9
+ # and commands). The Guard vets the synthesized code itself; this
10
+ # deny-list is the gate on what that code may resolve through the sealed
11
+ # context's coeffect/require path.
12
+ module SealedCoeffects
13
+ # Coeffects that must NEVER be leaked to synthesized code. Canonical
14
+ # keys (Rubik::Coeffects); legacy alias spellings canonicalize to their
15
+ # canonical form before the check, so aliases of a blocked service are
16
+ # denied without being restated here. App-domain coeffects (e.g.
17
+ # storage) stay reachable by design.
18
+ BLOCKED_COEFFECTS = [
19
+ "guard",
20
+ "config",
21
+ "sandbox",
22
+ "sandbox_runner",
23
+ "shell",
24
+ "buffer_manager",
25
+ "runtime_manager",
26
+ "task_manager",
27
+ "subagent_supervisor",
28
+ "init",
29
+ "dispatcher",
30
+ "commands",
31
+ "tool_registry",
32
+ "adapter_registry",
33
+ "mcp_manager",
34
+ "llm_client",
35
+ "router",
36
+ "plugin_manager",
37
+ "plugin_storage",
38
+ "lsp_manager",
39
+ "skill_manager"
40
+ ].freeze
41
+
42
+ private
43
+
44
+ # A legacy alias of a blocked service (e.g. "tools" for
45
+ # "tool_registry") must not slip through under the unblocked spelling.
46
+ # Denials log at warn: audible at the default level, since a blocked
47
+ # probe is a security event. Silence toward synthesized code (the
48
+ # command path and get/has?) is deliberate — the log is the operator
49
+ # record; the error class stays distinguishable host-side only.
50
+ def blocked?(key)
51
+ canonical = Rubik::Coeffects.canonical(key)
52
+ blocked = BLOCKED_COEFFECTS.include?(key) || BLOCKED_COEFFECTS.include?(canonical)
53
+ Rubik::Log.warn(:runtime, "sealed context denied coeffect '#{key}'") if blocked
54
+ blocked
55
+ end
56
+ end
57
+ end
58
+ end
@@ -0,0 +1,80 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "sealed_coeffects"
4
+
5
+ module Rubik
6
+ module Runtime
7
+ # Sealed execution context for synthesized and overlay commands (Pillar 2, Feature 11).
8
+ #
9
+ # Unlike the interactive REPL `CommandContext` (which exposes `guard`, `config`,
10
+ # `sandbox_runner`, `buffer_manager`, `shell`, and session mutations),
11
+ # `SynthesizedCommandContext` exposes ONLY:
12
+ # - Output methods: `out` (wrapped stream), `puts`, `print`, `flush` (and alias `output`)
13
+ # - Safe mediated coeffects: `coeffect(name)`
14
+ #
15
+ # All access to internal subsystems (.guard, .config, .sandbox_runner, .shell,
16
+ # .buffer_manager, .commands, etc.) is blocked; calling them raises NoMethodError.
17
+ class SynthesizedCommandContext
18
+ include SealedCoeffects
19
+
20
+ attr_reader :out
21
+ alias output out
22
+
23
+ def self.wrap(ctx, shell: nil, runtime_manager: nil)
24
+ return ctx if ctx.is_a?(self)
25
+
26
+ output_io = if ctx.respond_to?(:out) then ctx.out
27
+ elsif ctx then ctx
28
+ elsif shell.respond_to?(:output) then shell.output
29
+ else $stdout
30
+ end
31
+ runtime_ctx = if runtime_manager&.context then runtime_manager.context
32
+ elsif shell.respond_to?(:runtime_manager) then shell.runtime_manager&.context
33
+ elsif ctx.respond_to?(:runtime_manager) then ctx.runtime_manager&.context
34
+ end
35
+ new(output: output_io, coeffects: runtime_ctx || {})
36
+ end
37
+
38
+ def initialize(output: $stdout, coeffects: {})
39
+ @out = output || $stdout
40
+ @coeffects = coeffects || {}
41
+ end
42
+
43
+ # IO conveniences delegating to @out
44
+ def puts(*)
45
+ @out.puts(*)
46
+ end
47
+
48
+ def print(*)
49
+ @out.print(*)
50
+ end
51
+
52
+ def flush
53
+ @out.flush if @out.respond_to?(:flush)
54
+ end
55
+
56
+ # Safe mediated coeffect accessor.
57
+ # Returns nil if the coeffect is blocked or not satisfied.
58
+ def coeffect(name)
59
+ return nil if name.nil?
60
+
61
+ key = name.to_s.downcase.strip
62
+ return nil if blocked?(key)
63
+
64
+ if @coeffects.is_a?(Hash)
65
+ @coeffects[key] || @coeffects[name] || @coeffects[name.to_s] || @coeffects[name.to_sym]
66
+ elsif @coeffects.respond_to?(:get)
67
+ @coeffects.get(key)
68
+ elsif @coeffects.respond_to?(:resolve)
69
+ @coeffects.resolve(key)
70
+ elsif @coeffects.respond_to?(:[])
71
+ @coeffects[key] || @coeffects[name]
72
+ end
73
+ end
74
+ end
75
+ end
76
+
77
+ module REPL
78
+ SynthesizedCommandContext = Rubik::Runtime::SynthesizedCommandContext
79
+ end
80
+ end