rubik 0.9.0 → 0.10.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 (130) hide show
  1. checksums.yaml +4 -4
  2. data/ATTRIBUTION.md +1 -1
  3. data/CHANGELOG.md +250 -43
  4. data/README.md +5 -1
  5. data/lib/rubik/adapter/base.rb +21 -1
  6. data/lib/rubik/adapter/generic.rb +0 -14
  7. data/lib/rubik/adapter/node.rb +2 -0
  8. data/lib/rubik/adapter/process.rb +28 -67
  9. data/lib/rubik/ast/treesitter/zig_walker.rb +15 -2
  10. data/lib/rubik/benchmark/vakanuvis_adoption.rb +10 -3
  11. data/lib/rubik/buffer/apply_contract.rb +3 -3
  12. data/lib/rubik/buffer/apply_transaction.rb +165 -0
  13. data/lib/rubik/buffer/manager.rb +26 -120
  14. data/lib/rubik/cli/workspace_trust.rb +16 -0
  15. data/lib/rubik/config/deep_ops.rb +4 -1
  16. data/lib/rubik/config/defaults.rb +29 -3
  17. data/lib/rubik/config/schema.rb +8 -0
  18. data/lib/rubik/config/secret_policy.rb +197 -0
  19. data/lib/rubik/config/store.rb +14 -0
  20. data/lib/rubik/config.rb +11 -0
  21. data/lib/rubik/diagnostics/collector.rb +0 -9
  22. data/lib/rubik/errors.rb +15 -0
  23. data/lib/rubik/event_bus.rb +2 -1
  24. data/lib/rubik/kernel/dispatcher.rb +16 -11
  25. data/lib/rubik/kernel/unit.rb +4 -1
  26. data/lib/rubik/llm/registry.rb +12 -9
  27. data/lib/rubik/llm/router.rb +2 -5
  28. data/lib/rubik/log.rb +23 -1
  29. data/lib/rubik/lsp/client.rb +152 -445
  30. data/lib/rubik/lsp/document_store.rb +209 -0
  31. data/lib/rubik/lsp/manager.rb +14 -10
  32. data/lib/rubik/lsp/transport.rb +365 -0
  33. data/lib/rubik/mcp/boot_lifecycle.rb +6 -2
  34. data/lib/rubik/mcp/boot_run.rb +190 -0
  35. data/lib/rubik/mcp/client.rb +4 -3
  36. data/lib/rubik/mcp/manager.rb +46 -165
  37. data/lib/rubik/mcp/transport/stdio.rb +55 -10
  38. data/lib/rubik/orchestrator/auto_apply.rb +4 -3
  39. data/lib/rubik/orchestrator/continuation_manager.rb +3 -22
  40. data/lib/rubik/orchestrator/goal_session.rb +519 -0
  41. data/lib/rubik/orchestrator/loop.rb +28 -47
  42. data/lib/rubik/orchestrator/maestro_gate.rb +5 -7
  43. data/lib/rubik/orchestrator/provider_recovery.rb +4 -2
  44. data/lib/rubik/orchestrator/provider_resolver.rb +4 -2
  45. data/lib/rubik/orchestrator/resume_window.rb +96 -0
  46. data/lib/rubik/orchestrator/shell_deps.rb +16 -0
  47. data/lib/rubik/orchestrator/stream_manager.rb +2 -1
  48. data/lib/rubik/orchestrator/subagent/deferred_spec.rb +4 -1
  49. data/lib/rubik/orchestrator/subagent/instance.rb +11 -12
  50. data/lib/rubik/orchestrator/subagent/journal.rb +2 -1
  51. data/lib/rubik/orchestrator/subagent/lifecycle.rb +3 -1
  52. data/lib/rubik/orchestrator/subagent/questioner.rb +24 -7
  53. data/lib/rubik/orchestrator/subagent/reaper.rb +3 -5
  54. data/lib/rubik/orchestrator/subagent/resilience.rb +4 -2
  55. data/lib/rubik/orchestrator/subagent/result_archive.rb +0 -4
  56. data/lib/rubik/orchestrator/subagent/run_cycle.rb +2 -7
  57. data/lib/rubik/orchestrator/subagent/spawn_transaction.rb +11 -2
  58. data/lib/rubik/orchestrator/subagent/step_runner.rb +11 -3
  59. data/lib/rubik/orchestrator/subagent/teardown.rb +4 -0
  60. data/lib/rubik/orchestrator/subagent/transcript_formatter.rb +2 -1
  61. data/lib/rubik/orchestrator/subagent/type_definition.rb +0 -4
  62. data/lib/rubik/orchestrator/tool_timeout.rb +121 -1
  63. data/lib/rubik/orchestrator.rb +1 -0
  64. data/lib/rubik/platform/io_drain.rb +2 -1
  65. data/lib/rubik/platform/process.rb +144 -54
  66. data/lib/rubik/platform.rb +17 -1
  67. data/lib/rubik/plugin/manager.rb +2 -1
  68. data/lib/rubik/plugin/storage.rb +20 -29
  69. data/lib/rubik/repl/commands/agent_context.rb +9 -8
  70. data/lib/rubik/repl/commands/agent_execution.rb +20 -502
  71. data/lib/rubik/repl/commands/agent_models.rb +4 -3
  72. data/lib/rubik/repl/commands/agent_providers.rb +43 -2
  73. data/lib/rubik/repl/commands/base.rb +47 -2
  74. data/lib/rubik/repl/commands/buffer.rb +6 -5
  75. data/lib/rubik/repl/commands/lsp.rb +3 -2
  76. data/lib/rubik/repl/commands/pruner.rb +2 -1
  77. data/lib/rubik/repl/commands/secrets.rb +151 -0
  78. data/lib/rubik/repl/commands/workspace.rb +60 -150
  79. data/lib/rubik/repl/commands/workspace_approval.rb +209 -0
  80. data/lib/rubik/repl/config_wiring.rb +3 -3
  81. data/lib/rubik/repl/hooks.rb +2 -1
  82. data/lib/rubik/repl/input_execution.rb +158 -76
  83. data/lib/rubik/repl/input_loop.rb +3 -2
  84. data/lib/rubik/repl/lifecycle.rb +82 -204
  85. data/lib/rubik/repl/notice_router.rb +319 -0
  86. data/lib/rubik/repl/paste_support.rb +3 -1
  87. data/lib/rubik/repl/presentation.rb +5 -3
  88. data/lib/rubik/repl/pruner/gate.rb +3 -1
  89. data/lib/rubik/repl/pruner/harness.rb +2 -1
  90. data/lib/rubik/repl/shell.rb +4 -3
  91. data/lib/rubik/repl/turn_recorder.rb +6 -5
  92. data/lib/rubik/runtime/discovery.rb +3 -2
  93. data/lib/rubik/runtime/loop_service.rb +4 -3
  94. data/lib/rubik/runtime/manifest_store.rb +124 -0
  95. data/lib/rubik/runtime/overlay_guard.rb +127 -0
  96. data/lib/rubik/runtime/overlay_storage.rb +269 -272
  97. data/lib/rubik/runtime/task_manager.rb +71 -27
  98. data/lib/rubik/runtime.rb +1 -0
  99. data/lib/rubik/sandbox/driver/docker.rb +5 -1
  100. data/lib/rubik/sandbox/runner.rb +16 -15
  101. data/lib/rubik/security/allowlist.rb +167 -0
  102. data/lib/rubik/security/audit_log.rb +72 -0
  103. data/lib/rubik/security/classifier/classifier.rb +8 -0
  104. data/lib/rubik/security/command_gate.rb +591 -0
  105. data/lib/rubik/security/guard.rb +94 -1077
  106. data/lib/rubik/security/path_policy.rb +117 -0
  107. data/lib/rubik/security/secret_store.rb +463 -0
  108. data/lib/rubik/security/synthesis_gate.rb +297 -0
  109. data/lib/rubik/security.rb +5 -0
  110. data/lib/rubik/session/manager.rb +7 -1
  111. data/lib/rubik/skills/manager.rb +2 -3
  112. data/lib/rubik/storage/ranking.rb +113 -0
  113. data/lib/rubik/storage/search.rb +49 -0
  114. data/lib/rubik/storage/store.rb +15 -112
  115. data/lib/rubik/storage/transcript_indexer.rb +2 -3
  116. data/lib/rubik/storage/vakanuvis/harness.rb +2 -3
  117. data/lib/rubik/tools/base.rb +22 -0
  118. data/lib/rubik/tools/builtins/files.rb +3 -15
  119. data/lib/rubik/tools/builtins/grep.rb +3 -9
  120. data/lib/rubik/tools/builtins/lifecycle.rb +96 -92
  121. data/lib/rubik/tools/builtins/synthesis.rb +3 -0
  122. data/lib/rubik/tools/lifecycle_rollbacks.rb +100 -0
  123. data/lib/rubik/tools/native_search.rb +2 -1
  124. data/lib/rubik/tools/truncator.rb +73 -36
  125. data/lib/rubik/ui/banner.rb +4 -3
  126. data/lib/rubik/ui/spinner.rb +3 -1
  127. data/lib/rubik/ui/statusline.rb +6 -5
  128. data/lib/rubik/version.rb +1 -1
  129. data/lib/rubik.rb +1 -2
  130. metadata +23 -1
@@ -6,13 +6,29 @@ require "digest"
6
6
  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
+ require_relative "../errors"
9
10
  require_relative "../platform"
11
+ require_relative "../log"
12
+ require_relative "../plugin/package_inventory"
10
13
  require_relative "synthesized_command_context"
11
14
  require_relative "synthesized_tool_context"
15
+ require_relative "overlay_guard"
12
16
 
13
17
  module Rubik
14
18
  module Runtime
19
+ # Overlay manifest/lifecycle coordinator: directory layout, manifest CRUD,
20
+ # command/tool lifecycle, and the scrubbed-binding eval sink. The
21
+ # path-containment guards and the trust/bootstrap screening live on
22
+ # OverlayGuard (issue #447); the manifest primitives live on ManifestStore
23
+ # (issue #426, integrity records included).
15
24
  class OverlayStorage
25
+ # Registration refusal (issue #448): register_command silently returns
26
+ # false on a built-in name collision; eval_command turns that into
27
+ # this typed refusal so the [OVERLAY] fallback path and the loaded
28
+ # list stay honest. Callers rescue StandardError, so the class change
29
+ # is transparent to them.
30
+ class RegistrationRefusedError < Rubik::Error; end
31
+
16
32
  attr_reader :root_dir, :home_dir
17
33
 
18
34
  COMMAND_SENTINEL = "# Rubik Custom Command:"
@@ -21,12 +37,28 @@ module Rubik
21
37
  def initialize(root_dir: Dir.pwd, home_dir: ENV.fetch("HOME", nil), guard: nil, runtime_manager: nil, runtime_context: nil)
22
38
  @root_dir = File.expand_path(root_dir)
23
39
  @home_dir = File.expand_path(home_dir || ENV["HOME"] || ".")
24
- @guard = guard
25
40
  @runtime_manager = runtime_manager
26
41
  @runtime_context = runtime_context
42
+ # Issue #447: the guard/trust plane is OverlayGuard. The storage owns
43
+ # the directory layout and hands it over as a frozen table; the
44
+ # `guard:` kwarg seam is forwarded as-is (an injected synthesis guard
45
+ # — production's operator-policy guard, test spies — composes, never
46
+ # bypasses), and the ManifestStore trust-mode seam (issue #426) is
47
+ # injected as the single RUBIK_TRUST_OVERLAYS read.
48
+ @overlay_guard = OverlayGuard.new(allowed_dirs: allowed_overlay_dirs, guard: guard,
49
+ trust_mode: -> { manifest_store.trust_mode? })
27
50
  ensure_directories
28
51
  end
29
52
 
53
+ # Shared manifest primitives (issue #426) live on ManifestStore; this
54
+ # store wires the overlay-dir validation + containment checks into it.
55
+ def manifest_store
56
+ @manifest_store ||= ManifestStore.new(validate_path: lambda { |path, dir|
57
+ @overlay_guard.ensure_valid_overlay_dir!(dir)
58
+ @overlay_guard.ensure_contained_path!(path, dir)
59
+ })
60
+ end
61
+
30
62
  def project_commands_dir
31
63
  File.join(@root_dir, ".rubik", "commands")
32
64
  end
@@ -52,27 +84,15 @@ module Rubik
52
84
  end
53
85
 
54
86
  def manifest_path(dir)
55
- ensure_valid_overlay_dir!(dir)
56
- path = File.join(dir, ".manifest.json")
57
- ensure_contained_path!(path, dir)
58
- path
87
+ manifest_store.manifest_path(dir)
59
88
  end
60
89
 
61
90
  def load_manifest(dir)
62
- path = manifest_path(dir)
63
- return {} unless File.exist?(path)
64
-
65
- JSON.parse(File.read(path))
66
- rescue JSON::ParserError, ArgumentError
67
- {}
91
+ manifest_store.load_manifest(dir)
68
92
  end
69
93
 
70
94
  def save_manifest(dir, manifest)
71
- # Atomik yazım (tmp + rename): kilitsiz okuyucuların (load_manifest, manifest_state)
72
- # yarım manifest görmesini engeller; yarım okuma, kayıtlı overlay'lerin "unknown"
73
- # sayılıp kalıcı olarak reddedilmesine yol açabiliyordu. Platform.atomic_write,
74
- # Windows için unlink/rename yedeğiyle bu düzeni sağlar.
75
- Platform.atomic_write(manifest_path(dir), JSON.pretty_generate(manifest))
95
+ manifest_store.save_manifest(dir, manifest)
76
96
  end
77
97
 
78
98
  def normalize_content(raw)
@@ -80,29 +100,18 @@ module Rubik
80
100
  end
81
101
 
82
102
  def record_hash(dir, filename, scope)
83
- ensure_valid_overlay_dir!(dir)
84
- if manifest_state(dir) == :corrupt
85
- # Bozuk manifesti sessizce "heal" etmek (yalnızca yeni kaydı yazmak) diğer
86
- # kayıtlı overlay'leri tahliye eder; bunun yerine kaydı reddet.
87
- raise "cannot record '#{filename}': .manifest.json in #{dir} is corrupt; delete it and re-record overlays"
88
- end
103
+ refuse_corrupt_manifest!(dir, :record, filename)
89
104
 
90
105
  path = File.join(dir, filename)
91
- ensure_contained_path!(path, dir)
106
+ @overlay_guard.ensure_contained_path!(path, dir)
92
107
  hash = Digest::SHA256.hexdigest(normalize_content(File.binread(path)))
93
- manifest = load_manifest(dir)
94
- manifest[filename] = {
95
- "sha256" => hash,
96
- "scope" => scope.to_s,
97
- "created_at" => Time.now.iso8601
98
- }
99
- save_manifest(dir, manifest)
108
+ manifest_store.record_hash(dir, filename, hash, scope: scope)
100
109
  end
101
110
 
102
111
  def verify_integrity(file_path, dir, bootstrap_eligible: false)
103
- return :trusted if trust_mode?
112
+ return :trusted if @overlay_guard.trust_mode?
104
113
 
105
- unless safe_path_under?(file_path, dir)
114
+ unless @overlay_guard.safe_path_under?(file_path, dir)
106
115
  warn "[SECURITY] Path traversal attempt detected for overlay '#{file_path}'. Skipping."
107
116
  return :rejected
108
117
  end
@@ -112,86 +121,53 @@ module Rubik
112
121
  current_content = File.exist?(file_path) ? File.binread(file_path) : ""
113
122
  current_hash = Digest::SHA256.hexdigest(normalize_content(current_content))
114
123
 
115
- if manifest.key?(basename)
116
- # Known file — verify hash
124
+ case manifest_store.verify_entry(manifest, basename, current_hash)
125
+ when :verified
126
+ :verified
127
+ when :drift
128
+ # Constant-time comparison policy is single-homed in ManifestStore
129
+ # (issue #426), same as plugin verification.
117
130
  expected_hash = manifest[basename]["sha256"]
118
- if current_hash == expected_hash
119
- :verified
131
+ warn "[SECURITY] Integrity check failed for overlay '#{basename}': file modified " \
132
+ "since synthesis. Skipping. (expected: #{expected_hash}, got: #{current_hash})"
133
+ :rejected
134
+ when :unknown
135
+ if bootstrap_eligible && sentinel_content?(current_content)
136
+ # Bootstrap (tek seferlik): yalnızca manifest dosyasının hiç var olmadığı ilk taramada,
137
+ # sentinel başlıklı dosya kabul edilip hash'i manifest'e yazılır; uygunluk kararını
138
+ # verified_dir_entries taramanın başında verir. Manifest varken bootstrap asla çalışmaz.
139
+ # Kabul ÖNCE synthesis guard'ından geçer (Aday 07 ertelemesi): klonlanan depodaki
140
+ # dosya bu ortamda sentezlenmemişti; reddedilen dosya manifest'e yazılmaz.
141
+ verdict = @overlay_guard.screen_bootstrap_content(current_content, basename)
142
+ return verdict unless verdict == :ok
143
+
144
+ scope_match = current_content.match(/# Scope:\s*(.*)/)
145
+ scope = scope_match ? scope_match[1].strip : "unknown"
146
+
147
+ manifest[basename] = {
148
+ "sha256" => current_hash,
149
+ "scope" => scope,
150
+ "created_at" => Time.now.iso8601
151
+ }
152
+ save_manifest(dir, manifest)
153
+ :bootstrapped
120
154
  else
121
- warn "[SECURITY] Integrity check failed for overlay '#{basename}': file modified " \
122
- "since synthesis. Skipping. (expected: #{expected_hash}, got: #{current_hash})"
155
+ warn "[SECURITY] Unknown overlay file '#{basename}' not in manifest. Skipping."
123
156
  :rejected
124
157
  end
125
- elsif bootstrap_eligible && sentinel_content?(current_content)
126
- # Bootstrap (tek seferlik): yalnızca manifest dosyasının hiç var olmadığı ilk taramada,
127
- # sentinel başlıklı dosya kabul edilip hash'i manifest'e yazılır; uygunluk kararını
128
- # verified_dir_entries taramanın başında verir. Manifest varken bootstrap asla çalışmaz.
129
- # Kabul ÖNCE synthesis guard'ından geçer (Aday 07 ertelemesi): klonlanan depodaki
130
- # dosya bu ortamda sentezlenmemişti; reddedilen dosya manifest'e yazılmaz.
131
- verdict = screen_bootstrap_content(current_content, basename)
132
- return verdict unless verdict == :ok
133
-
134
- scope_match = current_content.match(/# Scope:\s*(.*)/)
135
- scope = scope_match ? scope_match[1].strip : "unknown"
136
-
137
- manifest[basename] = {
138
- "sha256" => current_hash,
139
- "scope" => scope,
140
- "created_at" => Time.now.iso8601
141
- }
142
- save_manifest(dir, manifest)
143
- :bootstrapped
144
- else
145
- warn "[SECURITY] Unknown overlay file '#{basename}' not in manifest. Skipping."
146
- :rejected
147
158
  end
148
159
  end
149
160
 
161
+ # Issue #407: the command/tool quadruplets collapse onto shared skeletons
162
+ # (save / delete / load_entries in the private section) behind the Kind
163
+ # adapter at the bottom of this class. Public surface unchanged: these
164
+ # delegators keep the exact pre-refactor signatures and per-kind defaults.
150
165
  def save_command(name, code, scope: :project, description: "Custom command")
151
- clean_name = name.to_s.downcase.delete_prefix("!").gsub(/[^a-z0-9_:]/, "_")
152
- target_dir = scope.to_sym == :global ? global_commands_dir : project_commands_dir
153
- FileUtils.mkdir_p(target_dir)
154
-
155
- filename = "#{clean_name.gsub(':', '_')}.rb"
156
- file_path = File.join(target_dir, filename)
157
- ensure_contained_path!(file_path, target_dir)
158
-
159
- header = <<~RUBY
160
- # frozen_string_literal: true
161
- #{COMMAND_SENTINEL} !#{clean_name}
162
- # Scope: #{scope}
163
- # Description: #{description}
164
-
165
- RUBY
166
-
167
- File.write(file_path, "#{header}#{code.strip}\n")
168
- record_hash(target_dir, filename, scope)
169
- { ok: true, path: file_path, name: clean_name, scope: scope }
170
- rescue StandardError => e
171
- { ok: false, error: e.message }
166
+ save(COMMAND_KIND, name, code, scope: scope, description: description)
172
167
  end
173
168
 
174
- # Delete a synthesized command from disk and manifest. Symmetric to
175
- # save_command: same clean_name normalization, scope→dir selection and
176
- # { ok:, error: } shape. Fail-closed on a corrupt manifest — never wipe
177
- # it with {} (mirror the record_hash guard on the save path).
178
169
  def delete_command(name, scope: :project)
179
- clean_name = name.to_s.downcase.delete_prefix("!").gsub(/[^a-z0-9_:]/, "_")
180
- target_dir = scope.to_sym == :global ? global_commands_dir : project_commands_dir
181
- filename = "#{clean_name.gsub(':', '_')}.rb"
182
- file_path = File.join(target_dir, filename)
183
- ensure_contained_path!(file_path, target_dir)
184
-
185
- raise "cannot delete '#{filename}': .manifest.json in #{target_dir} is corrupt; delete it and re-record overlays" if manifest_state(target_dir) == :corrupt
186
-
187
- manifest = load_manifest(target_dir)
188
- manifest.delete(filename)
189
- save_manifest(target_dir, manifest)
190
-
191
- FileUtils.rm_f(file_path)
192
- { ok: true, name: clean_name, scope: scope, path: file_path }
193
- rescue StandardError => e
194
- { ok: false, error: e.message }
170
+ delete(COMMAND_KIND, name, scope: scope)
195
171
  end
196
172
 
197
173
  def list_commands
@@ -201,34 +177,31 @@ module Rubik
201
177
  end
202
178
 
203
179
  def load_all(shell, _manager = nil)
204
- loaded = []
205
- list_commands.each do |cmd_meta|
206
- next if cmd_meta[:integrity] == :rejected
207
-
208
- file_path = cmd_meta[:path]
209
- cmd_name = cmd_meta[:name]
210
- target_dir = cmd_meta[:scope].to_sym == :global ? global_commands_dir : project_commands_dir
211
-
212
- begin
213
- ensure_contained_path!(file_path, target_dir)
214
- code = File.read(file_path)
215
- eval_command(shell, cmd_name, code, cmd_meta[:scope])
216
- loaded << cmd_name
217
- rescue StandardError => e
218
- warn "[OVERLAY] Failed to load custom command '#{cmd_name}' from #{file_path}: #{e.class}: #{e.message}"
219
- end
180
+ load_entries(COMMAND_KIND, list_commands) do |name, code, scope|
181
+ eval_command(shell, name, code, scope)
182
+ true
220
183
  end
221
- loaded
222
184
  end
223
185
 
224
186
  def eval_command(shell, cmd_name, code, scope)
225
- desc_match = code.match(/# Description:\s*(.*)/)
226
- description = desc_match ? desc_match[1].strip : "Custom #{scope} command"
187
+ description = overlay_description(code, scope, "command")
227
188
 
228
189
  proc_handler = if code.include?("->") || code.include?("lambda") || code.include?("proc")
229
- 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)
190
+ overlay_eval(code)
230
191
  else
231
- 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)
192
+ # Sealed default (issue #398): a bare body (no proc marker)
193
+ # used to be wrapped into the legacy 3-arity raw-shell shape;
194
+ # it is now wrapped into a SEALED 2-arity handler so default
195
+ # saves land on the SynthesizedCommandContext deny-list path
196
+ # below. The body's `output` channel is preserved — bound per
197
+ # invocation to the sealed context's output view, inside the
198
+ # wrapper's own scope (lambda-local, no shared binding
199
+ # mutation, clean_eval_binding isolation unchanged). `shell`
200
+ # is deliberately NOT bound: bare bodies referencing it now
201
+ # raise NameError — the intended hardening; the documented
202
+ # migration is authoring an explicit 3-arity proc (the
203
+ # operator-trusted escape hatch in the dispatch else branch).
204
+ overlay_eval("->(args, ctx) {\noutput = ctx.respond_to?(:out) ? ctx.out : nil\n#{code}\n}")
232
205
  end
233
206
 
234
207
  registered = shell.register_command(cmd_name, description: "#{description} [#{scope}]", custom: true) do |args, ctx|
@@ -257,6 +230,18 @@ module Rubik
257
230
  end
258
231
  proc_handler.call(args, sealed_ctx)
259
232
  else
233
+ # Trust model (issue #398): this branch serves EXPLICITLY authored
234
+ # 3-arity handlers only — bare-body saves are sealed by the default
235
+ # wrap above. Such a handler receives the RAW interactive
236
+ # CommandContext/shell (`guard`, `config`, `sandbox_runner`,
237
+ # `buffer_manager`, etc. reachable), so the SealedCoeffects
238
+ # deny-list does NOT apply here. That is the operator-trusted
239
+ # bootstrap contract, anchored to the same trust vocabulary as the
240
+ # eval sites above: guard-checked at synthesis (or bootstrap
241
+ # acceptance) AND disk hash verified against the manifest
242
+ # (verify_integrity), with RUBIK_TRUST_OVERLAYS=1 as the blanket
243
+ # operator override. Authoring a 3-arity proc remains the
244
+ # deliberate escape hatch — it must stay an explicit act.
260
245
  out_ctx = if ctx
261
246
  ctx
262
247
  elsif shell.respond_to?(:command_context)
@@ -270,59 +255,15 @@ module Rubik
270
255
  end
271
256
  # register_command, built-in çakışmasında sessizce false döner; red,
272
257
  # load_all'un [OVERLAY] yoluna düşsün ve loaded listesi doğru kalsın.
273
- raise "registration refused for '#{cmd_name}' (name collides with a built-in)" if registered == false
258
+ raise RegistrationRefusedError, "registration refused for '#{cmd_name}' (name collides with a built-in)" if registered == false
274
259
  end
275
260
 
276
261
  def save_tool(name, code, scope: :project, description: "Custom native tool", params_schema: nil, risk: :execute)
277
- clean_name = name.to_s.downcase.gsub(/[^a-z0-9_]/, "_")
278
- target_dir = scope.to_sym == :global ? global_tools_dir : project_tools_dir
279
- FileUtils.mkdir_p(target_dir)
280
-
281
- filename = "#{clean_name}.rb"
282
- file_path = File.join(target_dir, filename)
283
- ensure_contained_path!(file_path, target_dir)
284
-
285
- schema_json = params_schema ? JSON.dump(params_schema) : "{}"
286
- header = <<~RUBY
287
- # frozen_string_literal: true
288
- #{TOOL_SENTINEL} #{clean_name}
289
- # Scope: #{scope}
290
- # Risk: #{risk}
291
- # Description: #{description}
292
- # Schema: #{schema_json}
293
-
294
- RUBY
295
-
296
- File.write(file_path, "#{header}#{code.strip}\n")
297
- record_hash(target_dir, filename, scope)
298
- { ok: true, path: file_path, name: clean_name, scope: scope }
299
- rescue StandardError => e
300
- # Audit 1: surfaced to the caller as ok:false and logged under RUBIK_DEBUG.
301
- warn "[WARN] [OVERLAY] Failed to save tool '#{name}' to #{file_path}: #{e.class}: #{e.message}" if ENV["RUBIK_DEBUG"]
302
- { ok: false, error: e.message }
262
+ save(TOOL_KIND, name, code, scope: scope, description: description, params_schema: params_schema, risk: risk)
303
263
  end
304
264
 
305
- # Delete a synthesized tool from disk and manifest. Symmetric to
306
- # save_tool: same clean_name normalization, scope→dir selection and
307
- # { ok:, error: } shape. Fail-closed on a corrupt manifest — never wipe
308
- # it with {} (mirror the record_hash guard on the save path).
309
265
  def delete_tool(name, scope: :project)
310
- clean_name = name.to_s.downcase.gsub(/[^a-z0-9_]/, "_")
311
- target_dir = scope.to_sym == :global ? global_tools_dir : project_tools_dir
312
- filename = "#{clean_name}.rb"
313
- file_path = File.join(target_dir, filename)
314
- ensure_contained_path!(file_path, target_dir)
315
-
316
- raise "cannot delete '#{filename}': .manifest.json in #{target_dir} is corrupt; delete it and re-record overlays" if manifest_state(target_dir) == :corrupt
317
-
318
- manifest = load_manifest(target_dir)
319
- manifest.delete(filename)
320
- save_manifest(target_dir, manifest)
321
-
322
- FileUtils.rm_f(file_path)
323
- { ok: true, name: clean_name, scope: scope, path: file_path }
324
- rescue StandardError => e
325
- { ok: false, error: e.message }
266
+ delete(TOOL_KIND, name, scope: scope)
326
267
  end
327
268
 
328
269
  def list_tools
@@ -331,31 +272,17 @@ module Rubik
331
272
  end
332
273
 
333
274
  def load_tools(tool_registry, runtime_manager: nil, runtime_context: nil)
334
- loaded = []
335
- list_tools.each do |t_meta|
336
- next if t_meta[:integrity] == :rejected
337
-
338
- file_path = t_meta[:path]
339
- target_dir = t_meta[:scope].to_sym == :global ? global_tools_dir : project_tools_dir
340
- ensure_contained_path!(file_path, target_dir)
341
-
342
- code = File.read(t_meta[:path])
343
- tool_inst = eval_tool(t_meta[:name], code, t_meta[:scope], runtime_manager: runtime_manager, runtime_context: runtime_context)
344
- if tool_inst
345
- tool_registry.register(tool_inst, origin: :overlay)
346
- loaded << t_meta[:name]
347
- else
348
- warn "[OVERLAY] Custom tool '#{t_meta[:name]}' from #{t_meta[:path]} did not evaluate to a usable tool."
349
- end
350
- rescue StandardError => e
351
- warn "[OVERLAY] Failed to load custom tool '#{t_meta[:name]}' from #{t_meta[:path]}: #{e.class}: #{e.message}"
275
+ load_entries(TOOL_KIND, list_tools) do |name, code, scope|
276
+ tool_inst = eval_tool(name, code, scope, runtime_manager: runtime_manager, runtime_context: runtime_context)
277
+ next false unless tool_inst
278
+
279
+ tool_registry.register(tool_inst, origin: :overlay)
280
+ true
352
281
  end
353
- loaded
354
282
  end
355
283
 
356
284
  def eval_tool(name, code, scope, runtime_manager: nil, runtime_context: nil)
357
- desc_match = code.match(/# Description:\s*(.*)/)
358
- description = desc_match ? desc_match[1].strip : "Custom #{scope} tool"
285
+ description = overlay_description(code, scope, "tool")
359
286
 
360
287
  schema_match = code.match(/# Schema:\s*(.*)/)
361
288
  schema = if schema_match
@@ -380,7 +307,7 @@ module Rubik
380
307
  # dropping the tool at load.
381
308
  risk = :execute unless [:read, :write, :execute].include?(risk)
382
309
 
383
- 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)
310
+ evaluated = overlay_eval(code)
384
311
  if evaluated.is_a?(Class) && evaluated < Rubik::Tools::BaseTool
385
312
  evaluated.new
386
313
  elsif evaluated.respond_to?(:call)
@@ -408,98 +335,174 @@ module Rubik
408
335
  end
409
336
  end
410
337
 
338
+ # ── Kind adapter (issue #407, merged into the single class body by
339
+ # issue #447 — the re-opened class block is gone) ────────────────────
340
+ # Per-kind asymmetries it parameterizes: name normalization
341
+ # (name_regex/strip_bang/colon_ok — commands keep ':' in the name but
342
+ # substitute it in the filename), scope→dir selection
343
+ # (global_dir/project_dir; anything but :global is project), byte-exact
344
+ # header emission (sentinel/bang/metadata_lines), and the warn
345
+ # asymmetries (debug_warn on save failure, warn_on_unusable on load).
346
+ Kind = Struct.new(:label, :sentinel, :bang, :name_regex, :strip_bang, :colon_ok, :debug_warn,
347
+ :warn_on_unusable, :metadata_lines, :global_dir, :project_dir, keyword_init: true) do
348
+ def normalize_name(raw)
349
+ name = raw.to_s.downcase
350
+ name = name.delete_prefix("!") if strip_bang
351
+ name.gsub(name_regex, "_")
352
+ end
353
+
354
+ def filename_for(clean_name)
355
+ "#{colon_ok ? clean_name.gsub(':', '_') : clean_name}.rb"
356
+ end
357
+
358
+ # Byte-exact header template: frozen-string line, sentinel line, Scope,
359
+ # tool-only Risk/Schema lines around Description, trailing blank line.
360
+ # eval_* parse these lines back and the integrity manifest hashes the
361
+ # whole file, so every byte is contract (pinned by the header-bytes tests).
362
+ def header_lines(name:, scope:, description:, risk:, schema:)
363
+ lines = ["# frozen_string_literal: true",
364
+ "#{sentinel} #{bang}#{name}",
365
+ "# Scope: #{scope}"]
366
+ lines << "# Risk: #{risk}" if metadata_lines
367
+ lines << "# Description: #{description}"
368
+ lines << "# Schema: #{schema}" if metadata_lines
369
+ lines << ""
370
+ lines
371
+ end
372
+ end
373
+
374
+ COMMAND_KIND = Kind.new(label: "command", sentinel: COMMAND_SENTINEL, bang: "!", name_regex: /[^a-z0-9_:]/,
375
+ strip_bang: true, colon_ok: true, debug_warn: false, warn_on_unusable: false,
376
+ metadata_lines: false, global_dir: :global_commands_dir, project_dir: :project_commands_dir).freeze
377
+
378
+ TOOL_KIND = Kind.new(label: "tool", sentinel: TOOL_SENTINEL, bang: "", name_regex: /[^a-z0-9_]/,
379
+ strip_bang: false, colon_ok: false, debug_warn: true, warn_on_unusable: true,
380
+ metadata_lines: true, global_dir: :global_tools_dir, project_dir: :project_tools_dir).freeze
381
+
411
382
  private
412
383
 
413
- def ensure_valid_overlay_dir!(dir)
414
- allowed = [
384
+ # Directory layout → guard wiring (issue #447): the containment guard
385
+ # needs the legit overlay dirs and their trusted roots; the storage
386
+ # owns the layout, the guard owns the enforcement.
387
+ def allowed_overlay_dirs
388
+ [
415
389
  [project_commands_dir, @root_dir],
416
390
  [global_commands_dir, @home_dir],
417
391
  [project_tools_dir, @root_dir],
418
392
  [global_tools_dir, @home_dir]
419
- ]
420
- valid = allowed.any? do |allowed_dir, trusted_root|
421
- Platform.path_equal?(dir, allowed_dir) && Platform.resolved_path_under?(dir, trusted_root)
422
- end
423
- return if valid
393
+ ].freeze
394
+ end
395
+
396
+ # Single home of the fail-closed corrupt-manifest contract (issue #407,
397
+ # single-homed in ManifestStore by issue #426): record_hash and the
398
+ # delete skeleton refuse through this one raise. `verb` reproduces the
399
+ # per-site messages ("cannot record '...'" vs "cannot delete '...'");
400
+ # the rest of the template is verbatim shared.
401
+ def refuse_corrupt_manifest!(dir, verb, filename)
402
+ manifest_store.refuse_corrupt_manifest!(dir, verb, filename)
403
+ end
404
+
405
+ # Shared save skeleton (issue #407): mkdir → containment check → header →
406
+ # File.write → record_hash → { ok:, ... } → rescue { ok:false, error: }.
407
+ # Header bytes are load-bearing twice over (eval_* parse them back with
408
+ # regexes; the integrity manifest hashes the whole file), so emission must
409
+ # stay byte-identical (pinned by the header-bytes tests).
410
+ def save(kind, name, code, scope:, description:, params_schema: nil, risk: :execute)
411
+ clean_name = kind.normalize_name(name)
412
+ target_dir = kind_dir(kind, scope)
413
+ FileUtils.mkdir_p(target_dir)
424
414
 
425
- raise ArgumentError, "Invalid overlay directory: #{dir}"
426
- end
415
+ filename = kind.filename_for(clean_name)
416
+ file_path = File.join(target_dir, filename)
417
+ @overlay_guard.ensure_contained_path!(file_path, target_dir)
427
418
 
428
- def ensure_contained_path!(path, parent_dir)
429
- raise ArgumentError, "Path traversal attempt detected: #{path}" unless safe_path_under?(path, parent_dir)
419
+ header = kind.header_lines(name: clean_name, scope: scope, description: description,
420
+ risk: risk, schema: params_schema ? JSON.dump(params_schema) : "{}")
421
+ File.write(file_path, "#{header.join("\n")}\n#{code.strip}\n")
422
+ record_hash(target_dir, filename, scope)
423
+ { ok: true, path: file_path, name: clean_name, scope: scope }
424
+ rescue StandardError => e
425
+ # Audit 1: surfaced to the caller as ok:false; tool kind logs under RUBIK_DEBUG.
426
+ warn "[WARN] [OVERLAY] Failed to save #{kind.label} '#{name}' to #{file_path}: #{e.class}: #{e.message}" if kind.debug_warn && ENV["RUBIK_DEBUG"]
427
+ { ok: false, error: e.message }
430
428
  end
431
429
 
432
- def safe_path_under?(path, parent_dir)
433
- return false if path.nil? || parent_dir.nil?
434
-
435
- ensure_valid_overlay_dir!(parent_dir)
430
+ # Shared delete skeleton (issue #407). Symmetric to save for both kinds:
431
+ # same clean_name normalization, scope→dir selection and { ok:, error: }
432
+ # shape. Fail-closed on a corrupt manifest — never wipe it with {}
433
+ # (single-homed in refuse_corrupt_manifest! above).
434
+ def delete(kind, name, scope:)
435
+ clean_name = kind.normalize_name(name)
436
+ target_dir = kind_dir(kind, scope)
437
+ filename = kind.filename_for(clean_name)
438
+ file_path = File.join(target_dir, filename)
439
+ @overlay_guard.ensure_contained_path!(file_path, target_dir)
436
440
 
437
- # Lexical containment check first
438
- return false unless Platform.path_under?(path, parent_dir)
441
+ refuse_corrupt_manifest!(target_dir, :delete, filename)
439
442
 
440
- # If path exists or parent exists, also check resolved path containment
441
- return Platform.resolved_path_under?(path, parent_dir) if File.exist?(path) || File.exist?(parent_dir)
443
+ manifest = load_manifest(target_dir)
444
+ manifest.delete(filename)
445
+ save_manifest(target_dir, manifest)
442
446
 
443
- true
444
- rescue StandardError
445
- false
447
+ FileUtils.rm_f(file_path)
448
+ { ok: true, name: clean_name, scope: scope, path: file_path }
449
+ rescue StandardError => e
450
+ { ok: false, error: e.message }
446
451
  end
447
452
 
448
- # Bootstrap kabul taramasında kullanılacak guard: kwarg'la geçilen örnek
449
- # (üretimde service catalog'un tek operatör-policy guard'ı) ya da lazy
450
- # default. Lazy çözüm bilinçli: overlay_storage.rb standalone require
451
- # edilebilen bir dosyadır; security/guard yalnızca tarama gerçekten
452
- # gerektiğinde yüklenir, load-order denetimi gerekmez.
453
- def bootstrap_guard
454
- @bootstrap_guard ||= begin
455
- require_relative "../security/guard"
456
- @guard || Rubik::Security::Guard.new
453
+ # Shared load skeleton (issue #407): iterate the verified listing → skip
454
+ # rejected entries → containment check → read → evaluate via the block →
455
+ # collect → rescue+warn. The block decides what "registration" means per
456
+ # kind; a falsy result collects nothing and, for the tool kind
457
+ # (warn_on_unusable), warns "did not evaluate to a usable tool". Warn
458
+ # wording stays byte-identical to the pre-refactor messages.
459
+ def load_entries(kind, entries)
460
+ loaded = []
461
+ entries.each do |meta|
462
+ next if meta[:integrity] == :rejected
463
+
464
+ name = meta[:name]
465
+ file_path = meta[:path]
466
+ target_dir = kind_dir(kind, meta[:scope])
467
+
468
+ @overlay_guard.ensure_contained_path!(file_path, target_dir)
469
+ code = File.read(file_path)
470
+ if yield(name, code, meta[:scope])
471
+ loaded << name
472
+ elsif kind.warn_on_unusable
473
+ warn "[OVERLAY] Custom #{kind.label} '#{name}' from #{file_path} did not evaluate to a usable tool."
474
+ end
475
+ rescue StandardError => e
476
+ warn "[OVERLAY] Failed to load custom #{kind.label} '#{name}' from #{file_path}: #{e.class}: #{e.message}"
457
477
  end
478
+ loaded
458
479
  end
459
480
 
460
- # Aday 07'den ertelenen güvenlik kalemi: manifestsız dizindeki sentinel
461
- # dosya manifest'e yazılmadan önce synthesis guard'ından geçirilir.
462
- # Reddedilen (veya taranamayan) dosya manifest'e YAZILMAZ — sonraki tarama
463
- # yeniden tarar ve reddeder (sessiz heal, bozuk-manifest doktriniyle
464
- # çelişir); load_all/load_tools'un mevcut :rejected atlaması devreye girer.
465
- # Parse hatası guard içinde yutulur (çalıştırılamaz kod güvenlik olayı
466
- # değil); guard'ın kendisi patlarsa da dosya fail-closed reddedilir —
467
- # SystemStackError dahil: rakip içerikte derin yuvalama AST walk'ı
468
- # taşırebilir, tek dosyanın reddiyesi tüm taramayı çökertmemeli.
469
- # Bilinçli asimetri: dosyanın TAMAMI (Description/Schema başlığı dahil)
470
- # taranır — sentez anında yalnızca kod taranıyordu. Kabul kapısı daha
471
- # sıkı olmak güvenli yöndür; başlık metnine denk gelen nadir yanlış
472
- # pozitif dosyayı makinede yeniden kayıtla çözülür.
473
- # Emit doktrini (guard.rb run_synthesis_gate hükmü): güvenlik kararının
474
- # tek kullanıcı-yüzü izi $VERBOSE=nil altında da yaşamalıdır — $stderr.puts.
475
- def screen_bootstrap_content(content, basename)
476
- bootstrap_guard.verify_synthesis_safety!(content)
477
- :ok
478
- rescue Rubik::Security::BlockedWriteError => e
479
- $stderr.puts "[SECURITY] Bootstrap overlay '#{basename}' refused by synthesis guard: #{e.message}" # rubocop:disable Style/StderrPuts
480
- :rejected
481
- rescue StandardError, ScriptError, SystemStackError => e
482
- $stderr.puts "[SECURITY] Bootstrap overlay '#{basename}' could not be screened (#{e.class}: #{e.message}); refusing." # rubocop:disable Style/StderrPuts
483
- :rejected
484
- end
485
-
486
- # Ortak kaçış kapısı predicate'i: iki güvenlik kapısının (verify_integrity,
487
- # verified_dir_entries) kopya ENV kontrolüyle sürünerek ayrışmasını engeller.
488
- def trust_mode?
489
- ENV["RUBIK_TRUST_OVERLAYS"] == "1"
490
- end
491
-
492
- # Üç durumlu manifest yoklaması: :missing / :valid / :corrupt.
493
- # load_manifest bilinçli olarak değiştirilmedi; kayıt yolu (record_hash) ve
494
- # save_command/save_tool akışları bozuk manifestte {} davranışına bağlı kalıyor.
495
- def manifest_state(dir)
496
- path = manifest_path(dir)
497
- return :missing unless File.exist?(path)
481
+ # Shared header-field readback (issue #407): both eval paths recover the
482
+ # Description line with the same regex and default text.
483
+ def overlay_description(code, scope, kind_label)
484
+ desc_match = code.match(/# Description:\s*(.*)/)
485
+ desc_match ? desc_match[1].strip : "Custom #{scope} #{kind_label}"
486
+ end
487
+
488
+ # Single home of the overlay eval sink and its rubocop disable: the code
489
+ # is guard-checked at synthesis (or bootstrap acceptance) and its disk
490
+ # hash verified against the manifest before this runs.
491
+ def overlay_eval(code)
492
+ 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)
493
+ end
494
+
495
+ # Kind-scoped directory selection: anything but :global lands in the
496
+ # project tree (pre-refactor behavior for both kinds).
497
+ def kind_dir(kind, scope)
498
+ scope.to_sym == :global ? public_send(kind.global_dir) : public_send(kind.project_dir)
499
+ end
498
500
 
499
- parsed = JSON.parse(File.read(path))
500
- parsed.is_a?(Hash) ? :valid : :corrupt
501
- rescue JSON::ParserError
502
- :corrupt
501
+ # Üç durumlu manifest yoklaması ve bozuk-manifest reddi ManifestStore'da
502
+ # tek home'da (issue #426): kayıt yolu (record_hash) ve delete iskeleti
503
+ # bozuk manifestte {} davranışına değil, fail-closed redde bağlı.
504
+ def manifest_state(dir)
505
+ manifest_store.manifest_state(dir)
503
506
  end
504
507
 
505
508
  # Dizin taraması başına bootstrap uygunluğu: manifest dosyası hiç yokken sentinel
@@ -509,14 +512,14 @@ module Rubik
509
512
  files = Dir.glob(File.join(dir, "*.rb"))
510
513
 
511
514
  # Kaçış kapısı: trust modu manifest durumundan bağımsız olarak tüm dosyaları güvenilir sayar.
512
- return files.map { |f| { name: File.basename(f, ".rb"), scope: scope, path: f, integrity: :trusted } } if trust_mode?
515
+ return files.map { |f| { name: File.basename(f, ".rb"), scope: scope, path: f, integrity: :trusted } } if @overlay_guard.trust_mode?
513
516
 
514
517
  case manifest_state(dir)
515
518
  when :corrupt
516
519
  warn "[SECURITY] Corrupt manifest in #{dir}; skipping #{files.size} overlay(s)."
517
520
  []
518
521
  when :missing
519
- if bootstrap_opt_in?
522
+ if @overlay_guard.bootstrap_opt_in?
520
523
  bootstrapped = 0
521
524
  entries = files.map do |f|
522
525
  integrity = verify_integrity(f, dir, bootstrap_eligible: true)
@@ -543,12 +546,6 @@ module Rubik
543
546
  end
544
547
  end
545
548
 
546
- # İlk-bootstrap açık rızası: manifest'siz dizindeki sentinel dosyaların ilk taramada
547
- # kabul edilmesi ancak bu env ile mümkündür (kayıt kalıcıdır; sonraki açılışlar env'siz çalışır).
548
- def bootstrap_opt_in?
549
- ENV["RUBIK_BOOTSTRAP_OVERLAYS"] == "1"
550
- end
551
-
552
549
  def sentinel_content?(content)
553
550
  content.include?(COMMAND_SENTINEL) || content.include?(TOOL_SENTINEL)
554
551
  end