rubik 0.8.1 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. checksums.yaml +4 -4
  2. data/ATTRIBUTION.md +2 -2
  3. data/CHANGELOG.md +207 -43
  4. data/README.md +5 -1
  5. data/bin/rubik +15 -10
  6. data/lib/rubik/adapter/base.rb +19 -0
  7. data/lib/rubik/adapter/generic.rb +0 -14
  8. data/lib/rubik/adapter/node.rb +2 -0
  9. data/lib/rubik/ast/treesitter/zig_walker.rb +15 -2
  10. data/lib/rubik/cli/workspace_trust.rb +17 -0
  11. data/lib/rubik/concurrency/worker.rb +143 -0
  12. data/lib/rubik/concurrency.rb +1 -0
  13. data/lib/rubik/config/deep_ops.rb +17 -0
  14. data/lib/rubik/config/defaults.rb +23 -1
  15. data/lib/rubik/config/schema.rb +0 -1
  16. data/lib/rubik/config/store.rb +14 -0
  17. data/lib/rubik/config.rb +7 -3
  18. data/lib/rubik/context/repo_context_reader.rb +27 -8
  19. data/lib/rubik/events.rb +18 -0
  20. data/lib/rubik/kernel/dispatcher.rb +4 -4
  21. data/lib/rubik/kernel/unit.rb +4 -3
  22. data/lib/rubik/log.rb +2 -1
  23. data/lib/rubik/lsp/client.rb +83 -180
  24. data/lib/rubik/lsp/document_store.rb +209 -0
  25. data/lib/rubik/mcp/client.rb +4 -3
  26. data/lib/rubik/mcp/manager.rb +6 -2
  27. data/lib/rubik/mcp/transport/stdio.rb +51 -9
  28. data/lib/rubik/orchestrator/auto_apply.rb +2 -0
  29. data/lib/rubik/orchestrator/budget_manager.rb +18 -2
  30. data/lib/rubik/orchestrator/goal_ledger/deep_ops.rb +41 -0
  31. data/lib/rubik/orchestrator/goal_ledger/drift.rb +2 -1
  32. data/lib/rubik/orchestrator/goal_ledger/ledger.rb +56 -50
  33. data/lib/rubik/orchestrator/goal_ledger/observation_projection.rb +26 -0
  34. data/lib/rubik/orchestrator/goal_ledger/patch.rb +10 -17
  35. data/lib/rubik/orchestrator/goal_ledger/suspend_lifecycle.rb +9 -41
  36. data/lib/rubik/orchestrator/goal_ledger/validator.rb +6 -20
  37. data/lib/rubik/orchestrator/goal_ledger/verifier.rb +3 -14
  38. data/lib/rubik/orchestrator/goal_ledger/xml_render.rb +21 -14
  39. data/lib/rubik/orchestrator/goal_session.rb +505 -0
  40. data/lib/rubik/orchestrator/goal_state.rb +15 -15
  41. data/lib/rubik/orchestrator/loop.rb +62 -63
  42. data/lib/rubik/orchestrator/lsp_feedback.rb +7 -1
  43. data/lib/rubik/orchestrator/subagent/admission_policy.rb +161 -0
  44. data/lib/rubik/orchestrator/subagent/builtin_types.rb +3 -2
  45. data/lib/rubik/orchestrator/subagent/instance.rb +4 -0
  46. data/lib/rubik/orchestrator/subagent/journal.rb +2 -1
  47. data/lib/rubik/orchestrator/subagent/notices.rb +5 -4
  48. data/lib/rubik/orchestrator/subagent/profile_contract.rb +4 -10
  49. data/lib/rubik/orchestrator/subagent/questioner.rb +21 -6
  50. data/lib/rubik/orchestrator/subagent/run_cycle.rb +22 -1
  51. data/lib/rubik/orchestrator/subagent/scoped_registry.rb +34 -2
  52. data/lib/rubik/orchestrator/subagent/step_runner.rb +1 -1
  53. data/lib/rubik/orchestrator/subagent/teardown.rb +4 -0
  54. data/lib/rubik/orchestrator/subagent/transcript_formatter.rb +2 -1
  55. data/lib/rubik/orchestrator/subagent/type_registry.rb +19 -1
  56. data/lib/rubik/orchestrator/turn_executor/subagent_channel.rb +6 -1
  57. data/lib/rubik/orchestrator/turn_executor/user_channel.rb +6 -1
  58. data/lib/rubik/orchestrator/turn_executor.rb +2 -1
  59. data/lib/rubik/orchestrator.rb +1 -0
  60. data/lib/rubik/platform/path.rb +0 -1
  61. data/lib/rubik/platform.rb +15 -0
  62. data/lib/rubik/plugin/storage.rb +20 -29
  63. data/lib/rubik/prompt/context_builder.rb +24 -18
  64. data/lib/rubik/prompt/context_compactor.rb +31 -8
  65. data/lib/rubik/prompt/conversation_rows.rb +33 -0
  66. data/lib/rubik/prompt/doctrine.rb +4 -2
  67. data/lib/rubik/prompt/emergency_compactor.rb +5 -4
  68. data/lib/rubik/repl/commands/agent_context.rb +1 -1
  69. data/lib/rubik/repl/commands/agent_execution.rb +15 -467
  70. data/lib/rubik/repl/commands/buffer.rb +5 -1
  71. data/lib/rubik/repl/commands/lsp.rb +1 -1
  72. data/lib/rubik/repl/commands/mcp.rb +5 -0
  73. data/lib/rubik/repl/commands/subagents.rb +4 -4
  74. data/lib/rubik/repl/commands/workspace.rb +22 -2
  75. data/lib/rubik/repl/config_wiring.rb +24 -7
  76. data/lib/rubik/repl/input_execution.rb +1 -1
  77. data/lib/rubik/repl/input_loop.rb +1 -1
  78. data/lib/rubik/repl/lifecycle.rb +31 -2
  79. data/lib/rubik/repl/pruner/harness.rb +52 -67
  80. data/lib/rubik/repl/pruner/rules.rb +3 -1
  81. data/lib/rubik/repl/service_catalog.rb +1 -1
  82. data/lib/rubik/repl/synthesized_command_context.rb +3 -0
  83. data/lib/rubik/repl/turn_recorder.rb +5 -4
  84. data/lib/rubik/repl.rb +1 -0
  85. data/lib/rubik/runtime/context.rb +5 -0
  86. data/lib/rubik/runtime/discovery.rb +55 -0
  87. data/lib/rubik/runtime/manifest_store.rb +116 -0
  88. data/lib/rubik/runtime/overlay_storage.rb +300 -218
  89. data/lib/rubik/runtime/repair_probe.rb +20 -2
  90. data/lib/rubik/runtime/sealed_coeffects.rb +58 -0
  91. data/lib/rubik/runtime/synthesized_command_context.rb +80 -0
  92. data/lib/rubik/runtime/synthesized_tool_context.rb +123 -0
  93. data/lib/rubik/runtime/task_manager.rb +7 -2
  94. data/lib/rubik/runtime.rb +3 -0
  95. data/lib/rubik/security/allowlist.rb +167 -0
  96. data/lib/rubik/security/audit_log.rb +72 -0
  97. data/lib/rubik/security/classifier/classifier.rb +24 -8
  98. data/lib/rubik/security/classifier/commands/biome.yaml +49 -0
  99. data/lib/rubik/security/classifier/commands/bun.yaml +91 -0
  100. data/lib/rubik/security/classifier/commands/bundle.yaml +107 -0
  101. data/lib/rubik/security/classifier/commands/clang-format.yaml +21 -0
  102. data/lib/rubik/security/classifier/commands/clang.yaml +37 -0
  103. data/lib/rubik/security/classifier/commands/cmake.yaml +37 -0
  104. data/lib/rubik/security/classifier/commands/ctest.yaml +30 -0
  105. data/lib/rubik/security/classifier/commands/gcc.yaml +36 -0
  106. data/lib/rubik/security/classifier/commands/gem.yaml +104 -0
  107. data/lib/rubik/security/classifier/commands/gofmt.yaml +15 -0
  108. data/lib/rubik/security/classifier/commands/pnpm.yaml +8 -8
  109. data/lib/rubik/security/classifier/commands/python.yaml +18 -1
  110. data/lib/rubik/security/classifier/commands/python3.yaml +18 -1
  111. data/lib/rubik/security/classifier/commands/rake.yaml +60 -0
  112. data/lib/rubik/security/classifier/commands/rspec.yaml +42 -0
  113. data/lib/rubik/security/classifier/commands/rubocop.yaml +38 -0
  114. data/lib/rubik/security/classifier/commands/ruby.yaml +25 -0
  115. data/lib/rubik/security/classifier/commands/rustc.yaml +34 -0
  116. data/lib/rubik/security/classifier/commands/zig.yaml +77 -0
  117. data/lib/rubik/security/classifier/database.rb +12 -1
  118. data/lib/rubik/security/classifier/matcher.rb +17 -2
  119. data/lib/rubik/security/classifier/models.rb +3 -2
  120. data/lib/rubik/security/classifier.rb +5 -0
  121. data/lib/rubik/security/command_gate.rb +567 -0
  122. data/lib/rubik/security/guard.rb +96 -989
  123. data/lib/rubik/security/path_policy.rb +117 -0
  124. data/lib/rubik/security/synthesis_gate.rb +300 -0
  125. data/lib/rubik/security.rb +5 -0
  126. data/lib/rubik/storage/ranking.rb +113 -0
  127. data/lib/rubik/storage/store.rb +2 -92
  128. data/lib/rubik/storage/transcript_indexer.rb +2 -3
  129. data/lib/rubik/storage/vakanuvis/harness.rb +49 -89
  130. data/lib/rubik/tools/base.rb +24 -7
  131. data/lib/rubik/tools/builtins/files.rb +2 -0
  132. data/lib/rubik/tools/builtins/goal_ledger.rb +9 -9
  133. data/lib/rubik/tools/builtins/grep.rb +2 -3
  134. data/lib/rubik/tools/builtins/lifecycle.rb +91 -88
  135. data/lib/rubik/tools/builtins/synthesis.rb +124 -64
  136. data/lib/rubik/tools/builtins/unsynthesize.rb +38 -0
  137. data/lib/rubik/tools/catalog.rb +3 -0
  138. data/lib/rubik/tools/declaration.rb +6 -2
  139. data/lib/rubik/tools/lifecycle_rollbacks.rb +87 -0
  140. data/lib/rubik/tools/native_search.rb +2 -1
  141. data/lib/rubik/tools/preflight_runner.rb +107 -14
  142. data/lib/rubik/tools/registry.rb +2 -0
  143. data/lib/rubik/tools/truncator.rb +25 -0
  144. data/lib/rubik/tools/uri_resolver.rb +3 -1
  145. data/lib/rubik/uris.rb +5 -1
  146. data/lib/rubik/version.rb +1 -1
  147. data/lib/rubik.rb +1 -0
  148. metadata +35 -1
@@ -7,6 +7,9 @@ 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 "../plugin/package_inventory"
11
+ require_relative "synthesized_command_context"
12
+ require_relative "synthesized_tool_context"
10
13
 
11
14
  module Rubik
12
15
  module Runtime
@@ -16,13 +19,24 @@ module Rubik
16
19
  COMMAND_SENTINEL = "# Rubik Custom Command:"
17
20
  TOOL_SENTINEL = "# Rubik Custom Tool:"
18
21
 
19
- def initialize(root_dir: Dir.pwd, home_dir: ENV.fetch("HOME", nil), guard: nil)
22
+ def initialize(root_dir: Dir.pwd, home_dir: ENV.fetch("HOME", nil), guard: nil, runtime_manager: nil, runtime_context: nil)
20
23
  @root_dir = File.expand_path(root_dir)
21
24
  @home_dir = File.expand_path(home_dir || ENV["HOME"] || ".")
22
25
  @guard = guard
26
+ @runtime_manager = runtime_manager
27
+ @runtime_context = runtime_context
23
28
  ensure_directories
24
29
  end
25
30
 
31
+ # Shared manifest primitives (issue #426) live on ManifestStore; this
32
+ # store wires the overlay-dir validation + containment checks into it.
33
+ def manifest_store
34
+ @manifest_store ||= ManifestStore.new(validate_path: lambda { |path, dir|
35
+ ensure_valid_overlay_dir!(dir)
36
+ ensure_contained_path!(path, dir)
37
+ })
38
+ end
39
+
26
40
  def project_commands_dir
27
41
  File.join(@root_dir, ".rubik", "commands")
28
42
  end
@@ -48,27 +62,15 @@ module Rubik
48
62
  end
49
63
 
50
64
  def manifest_path(dir)
51
- ensure_valid_overlay_dir!(dir)
52
- path = File.join(dir, ".manifest.json")
53
- ensure_contained_path!(path, dir)
54
- path
65
+ manifest_store.manifest_path(dir)
55
66
  end
56
67
 
57
68
  def load_manifest(dir)
58
- path = manifest_path(dir)
59
- return {} unless File.exist?(path)
60
-
61
- JSON.parse(File.read(path))
62
- rescue JSON::ParserError, ArgumentError
63
- {}
69
+ manifest_store.load_manifest(dir)
64
70
  end
65
71
 
66
72
  def save_manifest(dir, manifest)
67
- # Atomik yazım (tmp + rename): kilitsiz okuyucuların (load_manifest, manifest_state)
68
- # yarım manifest görmesini engeller; yarım okuma, kayıtlı overlay'lerin "unknown"
69
- # sayılıp kalıcı olarak reddedilmesine yol açabiliyordu. Platform.atomic_write,
70
- # Windows için unlink/rename yedeğiyle bu düzeni sağlar.
71
- Platform.atomic_write(manifest_path(dir), JSON.pretty_generate(manifest))
73
+ manifest_store.save_manifest(dir, manifest)
72
74
  end
73
75
 
74
76
  def normalize_content(raw)
@@ -76,23 +78,12 @@ module Rubik
76
78
  end
77
79
 
78
80
  def record_hash(dir, filename, scope)
79
- ensure_valid_overlay_dir!(dir)
80
- if manifest_state(dir) == :corrupt
81
- # Bozuk manifesti sessizce "heal" etmek (yalnızca yeni kaydı yazmak) diğer
82
- # kayıtlı overlay'leri tahliye eder; bunun yerine kaydı reddet.
83
- raise "cannot record '#{filename}': .manifest.json in #{dir} is corrupt; delete it and re-record overlays"
84
- end
81
+ refuse_corrupt_manifest!(dir, :record, filename)
85
82
 
86
83
  path = File.join(dir, filename)
87
84
  ensure_contained_path!(path, dir)
88
85
  hash = Digest::SHA256.hexdigest(normalize_content(File.binread(path)))
89
- manifest = load_manifest(dir)
90
- manifest[filename] = {
91
- "sha256" => hash,
92
- "scope" => scope.to_s,
93
- "created_at" => Time.now.iso8601
94
- }
95
- save_manifest(dir, manifest)
86
+ manifest_store.record_hash(dir, filename, hash, scope: scope)
96
87
  end
97
88
 
98
89
  def verify_integrity(file_path, dir, bootstrap_eligible: false)
@@ -108,86 +99,53 @@ module Rubik
108
99
  current_content = File.exist?(file_path) ? File.binread(file_path) : ""
109
100
  current_hash = Digest::SHA256.hexdigest(normalize_content(current_content))
110
101
 
111
- if manifest.key?(basename)
112
- # Known file — verify hash
102
+ case manifest_store.verify_entry(manifest, basename, current_hash)
103
+ when :verified
104
+ :verified
105
+ when :drift
106
+ # Constant-time comparison policy is single-homed in ManifestStore
107
+ # (issue #426), same as plugin verification.
113
108
  expected_hash = manifest[basename]["sha256"]
114
- if current_hash == expected_hash
115
- :verified
109
+ warn "[SECURITY] Integrity check failed for overlay '#{basename}': file modified " \
110
+ "since synthesis. Skipping. (expected: #{expected_hash}, got: #{current_hash})"
111
+ :rejected
112
+ when :unknown
113
+ if bootstrap_eligible && sentinel_content?(current_content)
114
+ # Bootstrap (tek seferlik): yalnızca manifest dosyasının hiç var olmadığı ilk taramada,
115
+ # sentinel başlıklı dosya kabul edilip hash'i manifest'e yazılır; uygunluk kararını
116
+ # verified_dir_entries taramanın başında verir. Manifest varken bootstrap asla çalışmaz.
117
+ # Kabul ÖNCE synthesis guard'ından geçer (Aday 07 ertelemesi): klonlanan depodaki
118
+ # dosya bu ortamda sentezlenmemişti; reddedilen dosya manifest'e yazılmaz.
119
+ verdict = screen_bootstrap_content(current_content, basename)
120
+ return verdict unless verdict == :ok
121
+
122
+ scope_match = current_content.match(/# Scope:\s*(.*)/)
123
+ scope = scope_match ? scope_match[1].strip : "unknown"
124
+
125
+ manifest[basename] = {
126
+ "sha256" => current_hash,
127
+ "scope" => scope,
128
+ "created_at" => Time.now.iso8601
129
+ }
130
+ save_manifest(dir, manifest)
131
+ :bootstrapped
116
132
  else
117
- warn "[SECURITY] Integrity check failed for overlay '#{basename}': file modified " \
118
- "since synthesis. Skipping. (expected: #{expected_hash}, got: #{current_hash})"
133
+ warn "[SECURITY] Unknown overlay file '#{basename}' not in manifest. Skipping."
119
134
  :rejected
120
135
  end
121
- elsif bootstrap_eligible && sentinel_content?(current_content)
122
- # Bootstrap (tek seferlik): yalnızca manifest dosyasının hiç var olmadığı ilk taramada,
123
- # sentinel başlıklı dosya kabul edilip hash'i manifest'e yazılır; uygunluk kararını
124
- # verified_dir_entries taramanın başında verir. Manifest varken bootstrap asla çalışmaz.
125
- # Kabul ÖNCE synthesis guard'ından geçer (Aday 07 ertelemesi): klonlanan depodaki
126
- # dosya bu ortamda sentezlenmemişti; reddedilen dosya manifest'e yazılmaz.
127
- verdict = screen_bootstrap_content(current_content, basename)
128
- return verdict unless verdict == :ok
129
-
130
- scope_match = current_content.match(/# Scope:\s*(.*)/)
131
- scope = scope_match ? scope_match[1].strip : "unknown"
132
-
133
- manifest[basename] = {
134
- "sha256" => current_hash,
135
- "scope" => scope,
136
- "created_at" => Time.now.iso8601
137
- }
138
- save_manifest(dir, manifest)
139
- :bootstrapped
140
- else
141
- warn "[SECURITY] Unknown overlay file '#{basename}' not in manifest. Skipping."
142
- :rejected
143
136
  end
144
137
  end
145
138
 
139
+ # Issue #407: the command/tool quadruplets collapse onto shared skeletons
140
+ # (save / delete / load_entries in the private section) behind the Kind
141
+ # adapter at the bottom of this file. Public surface unchanged: these
142
+ # delegators keep the exact pre-refactor signatures and per-kind defaults.
146
143
  def save_command(name, code, scope: :project, description: "Custom command")
147
- clean_name = name.to_s.downcase.delete_prefix("!").gsub(/[^a-z0-9_:]/, "_")
148
- target_dir = scope.to_sym == :global ? global_commands_dir : project_commands_dir
149
- FileUtils.mkdir_p(target_dir)
150
-
151
- filename = "#{clean_name.gsub(':', '_')}.rb"
152
- file_path = File.join(target_dir, filename)
153
- ensure_contained_path!(file_path, target_dir)
154
-
155
- header = <<~RUBY
156
- # frozen_string_literal: true
157
- #{COMMAND_SENTINEL} !#{clean_name}
158
- # Scope: #{scope}
159
- # Description: #{description}
160
-
161
- RUBY
162
-
163
- File.write(file_path, "#{header}#{code.strip}\n")
164
- record_hash(target_dir, filename, scope)
165
- { ok: true, path: file_path, name: clean_name, scope: scope }
166
- rescue StandardError => e
167
- { ok: false, error: e.message }
144
+ save(COMMAND_KIND, name, code, scope: scope, description: description)
168
145
  end
169
146
 
170
- # Delete a synthesized command from disk and manifest. Symmetric to
171
- # save_command: same clean_name normalization, scope→dir selection and
172
- # { ok:, error: } shape. Fail-closed on a corrupt manifest — never wipe
173
- # it with {} (mirror the record_hash guard on the save path).
174
147
  def delete_command(name, scope: :project)
175
- clean_name = name.to_s.downcase.delete_prefix("!").gsub(/[^a-z0-9_:]/, "_")
176
- target_dir = scope.to_sym == :global ? global_commands_dir : project_commands_dir
177
- filename = "#{clean_name.gsub(':', '_')}.rb"
178
- file_path = File.join(target_dir, filename)
179
- ensure_contained_path!(file_path, target_dir)
180
-
181
- raise "cannot delete '#{filename}': .manifest.json in #{target_dir} is corrupt; delete it and re-record overlays" if manifest_state(target_dir) == :corrupt
182
-
183
- manifest = load_manifest(target_dir)
184
- manifest.delete(filename)
185
- save_manifest(target_dir, manifest)
186
-
187
- FileUtils.rm_f(file_path)
188
- { ok: true, name: clean_name, scope: scope, path: file_path }
189
- rescue StandardError => e
190
- { ok: false, error: e.message }
148
+ delete(COMMAND_KIND, name, scope: scope)
191
149
  end
192
150
 
193
151
  def list_commands
@@ -197,58 +155,79 @@ module Rubik
197
155
  end
198
156
 
199
157
  def load_all(shell, _manager = nil)
200
- loaded = []
201
- list_commands.each do |cmd_meta|
202
- next if cmd_meta[:integrity] == :rejected
203
-
204
- file_path = cmd_meta[:path]
205
- cmd_name = cmd_meta[:name]
206
- target_dir = cmd_meta[:scope].to_sym == :global ? global_commands_dir : project_commands_dir
207
-
208
- begin
209
- ensure_contained_path!(file_path, target_dir)
210
- code = File.read(file_path)
211
- eval_command(shell, cmd_name, code, cmd_meta[:scope])
212
- loaded << cmd_name
213
- rescue StandardError => e
214
- warn "[OVERLAY] Failed to load custom command '#{cmd_name}' from #{file_path}: #{e.class}: #{e.message}"
215
- end
158
+ load_entries(COMMAND_KIND, list_commands) do |name, code, scope|
159
+ eval_command(shell, name, code, scope)
160
+ true
216
161
  end
217
- loaded
218
162
  end
219
163
 
220
164
  def eval_command(shell, cmd_name, code, scope)
221
- desc_match = code.match(/# Description:\s*(.*)/)
222
- description = desc_match ? desc_match[1].strip : "Custom #{scope} command"
165
+ description = overlay_description(code, scope, "command")
223
166
 
224
167
  proc_handler = if code.include?("->") || code.include?("lambda") || code.include?("proc")
225
- eval(code, clean_eval_binding, __FILE__, __LINE__) # rubocop:disable Security/Eval -- overlay çekirdeği; sentez anında (veya bootstrap kabulünde) guard kontrolünden geçti VE disk hash'i manifestle doğrulandı (verify_integrity)
168
+ overlay_eval(code)
226
169
  else
227
- eval("->(args, output, shell) {\n#{code}\n}", clean_eval_binding, __FILE__, __LINE__) # rubocop:disable Security/Eval -- overlay çekirdeği; sentez anında (veya bootstrap kabulünde) guard kontrolünden geçti VE disk hash'i manifestle doğrulandı (verify_integrity)
170
+ # Sealed default (issue #398): a bare body (no proc marker)
171
+ # used to be wrapped into the legacy 3-arity raw-shell shape;
172
+ # it is now wrapped into a SEALED 2-arity handler so default
173
+ # saves land on the SynthesizedCommandContext deny-list path
174
+ # below. The body's `output` channel is preserved — bound per
175
+ # invocation to the sealed context's output view, inside the
176
+ # wrapper's own scope (lambda-local, no shared binding
177
+ # mutation, clean_eval_binding isolation unchanged). `shell`
178
+ # is deliberately NOT bound: bare bodies referencing it now
179
+ # raise NameError — the intended hardening; the documented
180
+ # migration is authoring an explicit 3-arity proc (the
181
+ # operator-trusted escape hatch in the dispatch else branch).
182
+ overlay_eval("->(args, ctx) {\noutput = ctx.respond_to?(:out) ? ctx.out : nil\n#{code}\n}")
228
183
  end
229
184
 
230
185
  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
186
  if proc_handler.arity == 1
248
187
  proc_handler.call(args)
249
188
  elsif proc_handler.arity == 2
250
- proc_handler.call(args, out_ctx)
189
+ warn "[rubik] overlay command invoked without a dispatch CommandContext" unless ctx || ENV["RUBIK_TEST"]
190
+ sealed_ctx = if ctx.is_a?(Rubik::REPL::SynthesizedCommandContext)
191
+ ctx
192
+ else
193
+ output_io = if ctx.respond_to?(:out)
194
+ ctx.out
195
+ elsif ctx
196
+ ctx
197
+ elsif shell.respond_to?(:output)
198
+ shell.output
199
+ else
200
+ $stdout
201
+ end
202
+ runtime_ctx = if shell.respond_to?(:runtime_manager)
203
+ shell.runtime_manager&.context
204
+ elsif ctx.respond_to?(:runtime_manager)
205
+ ctx.runtime_manager&.context
206
+ end
207
+ Rubik::REPL::SynthesizedCommandContext.new(output: output_io, coeffects: runtime_ctx || {})
208
+ end
209
+ proc_handler.call(args, sealed_ctx)
251
210
  else
211
+ # Trust model (issue #398): this branch serves EXPLICITLY authored
212
+ # 3-arity handlers only — bare-body saves are sealed by the default
213
+ # wrap above. Such a handler receives the RAW interactive
214
+ # CommandContext/shell (`guard`, `config`, `sandbox_runner`,
215
+ # `buffer_manager`, etc. reachable), so the SealedCoeffects
216
+ # deny-list does NOT apply here. That is the operator-trusted
217
+ # bootstrap contract, anchored to the same trust vocabulary as the
218
+ # eval sites above: guard-checked at synthesis (or bootstrap
219
+ # acceptance) AND disk hash verified against the manifest
220
+ # (verify_integrity), with RUBIK_TRUST_OVERLAYS=1 as the blanket
221
+ # operator override. Authoring a 3-arity proc remains the
222
+ # deliberate escape hatch — it must stay an explicit act.
223
+ out_ctx = if ctx
224
+ ctx
225
+ elsif shell.respond_to?(:command_context)
226
+ warn "[rubik] overlay command invoked without a dispatch CommandContext" unless ENV["RUBIK_TEST"]
227
+ shell.command_context
228
+ else
229
+ shell.output
230
+ end
252
231
  proc_handler.call(args, out_ctx.respond_to?(:out) ? out_ctx.out : out_ctx, shell)
253
232
  end
254
233
  end
@@ -258,55 +237,11 @@ module Rubik
258
237
  end
259
238
 
260
239
  def save_tool(name, code, scope: :project, description: "Custom native tool", params_schema: nil, risk: :execute)
261
- clean_name = name.to_s.downcase.gsub(/[^a-z0-9_]/, "_")
262
- target_dir = scope.to_sym == :global ? global_tools_dir : project_tools_dir
263
- FileUtils.mkdir_p(target_dir)
264
-
265
- filename = "#{clean_name}.rb"
266
- file_path = File.join(target_dir, filename)
267
- ensure_contained_path!(file_path, target_dir)
268
-
269
- schema_json = params_schema ? JSON.dump(params_schema) : "{}"
270
- header = <<~RUBY
271
- # frozen_string_literal: true
272
- #{TOOL_SENTINEL} #{clean_name}
273
- # Scope: #{scope}
274
- # Risk: #{risk}
275
- # Description: #{description}
276
- # Schema: #{schema_json}
277
-
278
- RUBY
279
-
280
- File.write(file_path, "#{header}#{code.strip}\n")
281
- record_hash(target_dir, filename, scope)
282
- { ok: true, path: file_path, name: clean_name, scope: scope }
283
- rescue StandardError => e
284
- # Audit 1: surfaced to the caller as ok:false and logged under RUBIK_DEBUG.
285
- warn "[WARN] [OVERLAY] Failed to save tool '#{name}' to #{file_path}: #{e.class}: #{e.message}" if ENV["RUBIK_DEBUG"]
286
- { ok: false, error: e.message }
240
+ save(TOOL_KIND, name, code, scope: scope, description: description, params_schema: params_schema, risk: risk)
287
241
  end
288
242
 
289
- # Delete a synthesized tool from disk and manifest. Symmetric to
290
- # save_tool: same clean_name normalization, scope→dir selection and
291
- # { ok:, error: } shape. Fail-closed on a corrupt manifest — never wipe
292
- # it with {} (mirror the record_hash guard on the save path).
293
243
  def delete_tool(name, scope: :project)
294
- clean_name = name.to_s.downcase.gsub(/[^a-z0-9_]/, "_")
295
- target_dir = scope.to_sym == :global ? global_tools_dir : project_tools_dir
296
- filename = "#{clean_name}.rb"
297
- file_path = File.join(target_dir, filename)
298
- ensure_contained_path!(file_path, target_dir)
299
-
300
- raise "cannot delete '#{filename}': .manifest.json in #{target_dir} is corrupt; delete it and re-record overlays" if manifest_state(target_dir) == :corrupt
301
-
302
- manifest = load_manifest(target_dir)
303
- manifest.delete(filename)
304
- save_manifest(target_dir, manifest)
305
-
306
- FileUtils.rm_f(file_path)
307
- { ok: true, name: clean_name, scope: scope, path: file_path }
308
- rescue StandardError => e
309
- { ok: false, error: e.message }
244
+ delete(TOOL_KIND, name, scope: scope)
310
245
  end
311
246
 
312
247
  def list_tools
@@ -314,38 +249,28 @@ module Rubik
314
249
  verified_dir_entries(project_tools_dir, :project)
315
250
  end
316
251
 
317
- def load_tools(tool_registry)
318
- loaded = []
319
- list_tools.each do |t_meta|
320
- next if t_meta[:integrity] == :rejected
252
+ def load_tools(tool_registry, runtime_manager: nil, runtime_context: nil)
253
+ load_entries(TOOL_KIND, list_tools) do |name, code, scope|
254
+ tool_inst = eval_tool(name, code, scope, runtime_manager: runtime_manager, runtime_context: runtime_context)
255
+ next false unless tool_inst
321
256
 
322
- file_path = t_meta[:path]
323
- target_dir = t_meta[:scope].to_sym == :global ? global_tools_dir : project_tools_dir
324
- ensure_contained_path!(file_path, target_dir)
325
-
326
- code = File.read(t_meta[:path])
327
- tool_inst = eval_tool(t_meta[:name], code, t_meta[:scope])
328
- if tool_inst
329
- tool_registry.register(tool_inst, origin: :overlay)
330
- loaded << t_meta[:name]
331
- else
332
- warn "[OVERLAY] Custom tool '#{t_meta[:name]}' from #{t_meta[:path]} did not evaluate to a usable tool."
333
- end
334
- rescue StandardError => e
335
- warn "[OVERLAY] Failed to load custom tool '#{t_meta[:name]}' from #{t_meta[:path]}: #{e.class}: #{e.message}"
257
+ tool_registry.register(tool_inst, origin: :overlay)
258
+ true
336
259
  end
337
- loaded
338
260
  end
339
261
 
340
- def eval_tool(name, code, scope)
341
- desc_match = code.match(/# Description:\s*(.*)/)
342
- description = desc_match ? desc_match[1].strip : "Custom #{scope} tool"
262
+ def eval_tool(name, code, scope, runtime_manager: nil, runtime_context: nil)
263
+ description = overlay_description(code, scope, "tool")
343
264
 
344
265
  schema_match = code.match(/# Schema:\s*(.*)/)
345
266
  schema = if schema_match
346
267
  begin
347
268
  JSON.parse(schema_match[1])
348
269
  rescue JSON::ParserError
270
+ # A malformed schema silently claiming "no arguments"
271
+ # hides real overlay bugs; keep loading (the tool is
272
+ # hash-verified) but say so.
273
+ warn "[rubik] overlay tool '#{name}' has a malformed '# Schema:' header; treating as no-arg schema"
349
274
  {}
350
275
  end
351
276
  else
@@ -360,18 +285,29 @@ module Rubik
360
285
  # dropping the tool at load.
361
286
  risk = :execute unless [:read, :write, :execute].include?(risk)
362
287
 
363
- evaluated = eval(code, clean_eval_binding, __FILE__, __LINE__) # rubocop:disable Security/Eval -- overlay çekirdeği; sentez anında (veya bootstrap kabulünde) guard kontrolünden geçti VE disk hash'i manifestle doğrulandı (verify_integrity)
288
+ evaluated = overlay_eval(code)
364
289
  if evaluated.is_a?(Class) && evaluated < Rubik::Tools::BaseTool
365
290
  evaluated.new
366
291
  elsif evaluated.respond_to?(:call)
292
+ runtime_mgr = runtime_manager || @runtime_manager
293
+ runtime_ctx = runtime_context || @runtime_context || (runtime_mgr&.context if runtime_mgr.respond_to?(:context)) || Rubik::Runtime::Context.new
367
294
  Class.new(Rubik::Tools::BaseTool) do
368
295
  define_method(:initialize) do
369
296
  super(name: name, description: "#{description} [#{scope}]", risk: risk, params_schema: schema)
370
297
  @handler = evaluated
298
+ @runtime_context = runtime_ctx
371
299
  end
372
300
 
373
- define_method(:execute) do |args = {}|
374
- @handler.call(args)
301
+ define_method(:execute) do |args = {}, ctx = nil|
302
+ if @handler.respond_to?(:arity) && @handler.arity.zero?
303
+ @handler.call
304
+ elsif Rubik::Runtime::SynthesizedToolContext.accepts_context?(@handler)
305
+ effective_ctx = ctx || @runtime_context || Rubik::Runtime::Context.new
306
+ sealed_ctx = Rubik::Runtime::SynthesizedToolContext.wrap(effective_ctx)
307
+ @handler.call(args, sealed_ctx)
308
+ else
309
+ @handler.call(args)
310
+ end
375
311
  end
376
312
  end.new
377
313
  end
@@ -379,6 +315,111 @@ module Rubik
379
315
 
380
316
  private
381
317
 
318
+ # Single home of the fail-closed corrupt-manifest contract (issue #407,
319
+ # single-homed in ManifestStore by issue #426): record_hash and the
320
+ # delete skeleton refuse through this one raise. `verb` reproduces the
321
+ # per-site messages ("cannot record '...'" vs "cannot delete '...'");
322
+ # the rest of the template is verbatim shared.
323
+ def refuse_corrupt_manifest!(dir, verb, filename)
324
+ manifest_store.refuse_corrupt_manifest!(dir, verb, filename)
325
+ end
326
+
327
+ # Shared save skeleton (issue #407): mkdir → containment check → header →
328
+ # File.write → record_hash → { ok:, ... } → rescue { ok:false, error: }.
329
+ # Header bytes are load-bearing twice over (eval_* parse them back with
330
+ # regexes; the integrity manifest hashes the whole file), so emission must
331
+ # stay byte-identical (pinned by the header-bytes tests).
332
+ def save(kind, name, code, scope:, description:, params_schema: nil, risk: :execute)
333
+ clean_name = kind.normalize_name(name)
334
+ target_dir = kind_dir(kind, scope)
335
+ FileUtils.mkdir_p(target_dir)
336
+
337
+ filename = kind.filename_for(clean_name)
338
+ file_path = File.join(target_dir, filename)
339
+ ensure_contained_path!(file_path, target_dir)
340
+
341
+ header = kind.header_lines(name: clean_name, scope: scope, description: description,
342
+ risk: risk, schema: params_schema ? JSON.dump(params_schema) : "{}")
343
+ File.write(file_path, "#{header.join("\n")}\n#{code.strip}\n")
344
+ record_hash(target_dir, filename, scope)
345
+ { ok: true, path: file_path, name: clean_name, scope: scope }
346
+ rescue StandardError => e
347
+ # Audit 1: surfaced to the caller as ok:false; tool kind logs under RUBIK_DEBUG.
348
+ warn "[WARN] [OVERLAY] Failed to save #{kind.label} '#{name}' to #{file_path}: #{e.class}: #{e.message}" if kind.debug_warn && ENV["RUBIK_DEBUG"]
349
+ { ok: false, error: e.message }
350
+ end
351
+
352
+ # Shared delete skeleton (issue #407). Symmetric to save for both kinds:
353
+ # same clean_name normalization, scope→dir selection and { ok:, error: }
354
+ # shape. Fail-closed on a corrupt manifest — never wipe it with {}
355
+ # (single-homed in refuse_corrupt_manifest! above).
356
+ def delete(kind, name, scope:)
357
+ clean_name = kind.normalize_name(name)
358
+ target_dir = kind_dir(kind, scope)
359
+ filename = kind.filename_for(clean_name)
360
+ file_path = File.join(target_dir, filename)
361
+ ensure_contained_path!(file_path, target_dir)
362
+
363
+ refuse_corrupt_manifest!(target_dir, :delete, filename)
364
+
365
+ manifest = load_manifest(target_dir)
366
+ manifest.delete(filename)
367
+ save_manifest(target_dir, manifest)
368
+
369
+ FileUtils.rm_f(file_path)
370
+ { ok: true, name: clean_name, scope: scope, path: file_path }
371
+ rescue StandardError => e
372
+ { ok: false, error: e.message }
373
+ end
374
+
375
+ # Shared load skeleton (issue #407): iterate the verified listing → skip
376
+ # rejected entries → containment check → read → evaluate via the block →
377
+ # collect → rescue+warn. The block decides what "registration" means per
378
+ # kind; a falsy result collects nothing and, for the tool kind
379
+ # (warn_on_unusable), warns "did not evaluate to a usable tool". Warn
380
+ # wording stays byte-identical to the pre-refactor messages.
381
+ def load_entries(kind, entries)
382
+ loaded = []
383
+ entries.each do |meta|
384
+ next if meta[:integrity] == :rejected
385
+
386
+ name = meta[:name]
387
+ file_path = meta[:path]
388
+ target_dir = kind_dir(kind, meta[:scope])
389
+
390
+ ensure_contained_path!(file_path, target_dir)
391
+ code = File.read(file_path)
392
+ if yield(name, code, meta[:scope])
393
+ loaded << name
394
+ elsif kind.warn_on_unusable
395
+ warn "[OVERLAY] Custom #{kind.label} '#{name}' from #{file_path} did not evaluate to a usable tool."
396
+ end
397
+ rescue StandardError => e
398
+ warn "[OVERLAY] Failed to load custom #{kind.label} '#{name}' from #{file_path}: #{e.class}: #{e.message}"
399
+ end
400
+ loaded
401
+ end
402
+
403
+ # Shared header-field readback (issue #407): both eval paths recover the
404
+ # Description line with the same regex and default text.
405
+ def overlay_description(code, scope, kind_label)
406
+ desc_match = code.match(/# Description:\s*(.*)/)
407
+ desc_match ? desc_match[1].strip : "Custom #{scope} #{kind_label}"
408
+ end
409
+
410
+ # Single home of the overlay eval sink and its rubocop disable: the code
411
+ # is guard-checked at synthesis (or bootstrap acceptance) and its disk
412
+ # hash verified against the manifest before this runs.
413
+ def overlay_eval(code)
414
+ eval(code, clean_eval_binding, __FILE__, __LINE__) # rubocop:disable Security/Eval -- overlay çekirdeği; sentez anında (veya bootstrap kabulünde) guard kontrolünden geçti VE disk hash'i manifestle doğrulandı (verify_integrity)
415
+ end
416
+
417
+ # Kind-scoped directory selection: anything but :global lands in the
418
+ # project tree (pre-refactor behavior for both kinds).
419
+ def kind_dir(kind, scope)
420
+ scope.to_sym == :global ? public_send(kind.global_dir) : public_send(kind.project_dir)
421
+ end
422
+
382
423
  def ensure_valid_overlay_dir!(dir)
383
424
  allowed = [
384
425
  [project_commands_dir, @root_dir],
@@ -454,21 +495,16 @@ module Rubik
454
495
 
455
496
  # Ortak kaçış kapısı predicate'i: iki güvenlik kapısının (verify_integrity,
456
497
  # verified_dir_entries) kopya ENV kontrolüyle sürünerek ayrışmasını engeller.
498
+ # Tek seam ManifestStore'da yaşar (issue #426); plugin tarafı da aynı kapıdan geçer.
457
499
  def trust_mode?
458
- ENV["RUBIK_TRUST_OVERLAYS"] == "1"
500
+ manifest_store.trust_mode?
459
501
  end
460
502
 
461
- # Üç durumlu manifest yoklaması: :missing / :valid / :corrupt.
462
- # load_manifest bilinçli olarak değiştirilmedi; kayıt yolu (record_hash) ve
463
- # save_command/save_tool akışları bozuk manifestte {} davranışına bağlı kalıyor.
503
+ # Üç durumlu manifest yoklaması ve bozuk-manifest reddi ManifestStore'da
504
+ # tek home'da (issue #426): kayıt yolu (record_hash) ve delete iskeleti
505
+ # bozuk manifestte {} davranışına değil, fail-closed redde bağlı.
464
506
  def manifest_state(dir)
465
- path = manifest_path(dir)
466
- return :missing unless File.exist?(path)
467
-
468
- parsed = JSON.parse(File.read(path))
469
- parsed.is_a?(Hash) ? :valid : :corrupt
470
- rescue JSON::ParserError
471
- :corrupt
507
+ manifest_store.manifest_state(dir)
472
508
  end
473
509
 
474
510
  # Dizin taraması başına bootstrap uygunluğu: manifest dosyası hiç yokken sentinel
@@ -534,5 +570,51 @@ module Rubik
534
570
  Object.new.instance_eval { binding }
535
571
  end
536
572
  end
573
+
574
+ # ── Private Kind adapter (issue #407) ──────────────────────────────────────
575
+ # Defined at the bottom so the frozen instances below can reference the
576
+ # sentinel constants declared in the class body above. Per-kind asymmetries
577
+ # it parameterizes: name normalization (name_regex/strip_bang/colon_ok —
578
+ # commands keep ':' in the name but substitute it in the filename), scope→
579
+ # dir selection (global_dir/project_dir; anything but :global is project),
580
+ # byte-exact header emission (sentinel/bang/metadata_lines), and the warn
581
+ # asymmetries (debug_warn on save failure, warn_on_unusable on load).
582
+ class OverlayStorage
583
+ Kind = Struct.new(:label, :sentinel, :bang, :name_regex, :strip_bang, :colon_ok, :debug_warn,
584
+ :warn_on_unusable, :metadata_lines, :global_dir, :project_dir, keyword_init: true) do
585
+ def normalize_name(raw)
586
+ name = raw.to_s.downcase
587
+ name = name.delete_prefix("!") if strip_bang
588
+ name.gsub(name_regex, "_")
589
+ end
590
+
591
+ def filename_for(clean_name)
592
+ "#{colon_ok ? clean_name.gsub(':', '_') : clean_name}.rb"
593
+ end
594
+
595
+ # Byte-exact header template: frozen-string line, sentinel line, Scope,
596
+ # tool-only Risk/Schema lines around Description, trailing blank line.
597
+ # eval_* parse these lines back and the integrity manifest hashes the
598
+ # whole file, so every byte is contract (pinned by the header-bytes tests).
599
+ def header_lines(name:, scope:, description:, risk:, schema:)
600
+ lines = ["# frozen_string_literal: true",
601
+ "#{sentinel} #{bang}#{name}",
602
+ "# Scope: #{scope}"]
603
+ lines << "# Risk: #{risk}" if metadata_lines
604
+ lines << "# Description: #{description}"
605
+ lines << "# Schema: #{schema}" if metadata_lines
606
+ lines << ""
607
+ lines
608
+ end
609
+ end
610
+
611
+ COMMAND_KIND = Kind.new(label: "command", sentinel: COMMAND_SENTINEL, bang: "!", name_regex: /[^a-z0-9_:]/,
612
+ strip_bang: true, colon_ok: true, debug_warn: false, warn_on_unusable: false,
613
+ metadata_lines: false, global_dir: :global_commands_dir, project_dir: :project_commands_dir).freeze
614
+
615
+ TOOL_KIND = Kind.new(label: "tool", sentinel: TOOL_SENTINEL, bang: "", name_regex: /[^a-z0-9_]/,
616
+ strip_bang: false, colon_ok: false, debug_warn: true, warn_on_unusable: true,
617
+ metadata_lines: true, global_dir: :global_tools_dir, project_dir: :project_tools_dir).freeze
618
+ end
537
619
  end
538
620
  end