rubik 0.9.1 → 0.11.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 (138) hide show
  1. checksums.yaml +4 -4
  2. data/ATTRIBUTION.md +1 -1
  3. data/CHANGELOG.md +203 -1
  4. data/lib/rubik/adapter/base.rb +2 -1
  5. data/lib/rubik/adapter/process.rb +28 -67
  6. data/lib/rubik/ast/extractor.rb +2 -1
  7. data/lib/rubik/ast/treesitter_extractor.rb +2 -1
  8. data/lib/rubik/benchmark/vakanuvis_adoption.rb +12 -4
  9. data/lib/rubik/buffer/apply_contract.rb +3 -3
  10. data/lib/rubik/buffer/apply_transaction.rb +165 -0
  11. data/lib/rubik/buffer/manager.rb +26 -120
  12. data/lib/rubik/config/deep_ops.rb +4 -1
  13. data/lib/rubik/config/defaults.rb +6 -3
  14. data/lib/rubik/config/schema.rb +8 -0
  15. data/lib/rubik/config/secret_policy.rb +198 -0
  16. data/lib/rubik/config/store.rb +2 -1
  17. data/lib/rubik/config.rb +13 -2
  18. data/lib/rubik/context/ignore_rules.rb +193 -0
  19. data/lib/rubik/context/scanner.rb +46 -161
  20. data/lib/rubik/diagnostics/collector.rb +0 -9
  21. data/lib/rubik/errors.rb +15 -0
  22. data/lib/rubik/event_bus.rb +2 -1
  23. data/lib/rubik/kernel/dispatcher.rb +12 -7
  24. data/lib/rubik/kernel/unit.rb +4 -1
  25. data/lib/rubik/llm/client.rb +6 -200
  26. data/lib/rubik/llm/connection_pool.rb +104 -0
  27. data/lib/rubik/llm/registry.rb +13 -9
  28. data/lib/rubik/llm/router.rb +2 -5
  29. data/lib/rubik/llm/sse_parser.rb +110 -0
  30. data/lib/rubik/log.rb +21 -0
  31. data/lib/rubik/lsp/circuit_breaker.rb +98 -0
  32. data/lib/rubik/lsp/client.rb +77 -273
  33. data/lib/rubik/lsp/client_provisioner.rb +49 -0
  34. data/lib/rubik/lsp/manager.rb +67 -96
  35. data/lib/rubik/lsp/transport.rb +365 -0
  36. data/lib/rubik/mcp/boot_lifecycle.rb +6 -2
  37. data/lib/rubik/mcp/boot_run.rb +190 -0
  38. data/lib/rubik/mcp/manager.rb +55 -166
  39. data/lib/rubik/mcp/transport/stdio.rb +4 -1
  40. data/lib/rubik/orchestrator/auto_apply.rb +8 -6
  41. data/lib/rubik/orchestrator/continuation_manager.rb +3 -22
  42. data/lib/rubik/orchestrator/goal_ledger/ledger.rb +12 -1
  43. data/lib/rubik/orchestrator/goal_ledger/schema_vocabulary.rb +38 -0
  44. data/lib/rubik/orchestrator/goal_ledger/xml_render.rb +6 -1
  45. data/lib/rubik/orchestrator/goal_ledger.rb +1 -0
  46. data/lib/rubik/orchestrator/goal_session.rb +53 -39
  47. data/lib/rubik/orchestrator/loop.rb +28 -47
  48. data/lib/rubik/orchestrator/lsp_feedback.rb +1 -1
  49. data/lib/rubik/orchestrator/maestro_gate.rb +5 -7
  50. data/lib/rubik/orchestrator/provider_recovery.rb +4 -2
  51. data/lib/rubik/orchestrator/provider_resolver.rb +4 -2
  52. data/lib/rubik/orchestrator/resume_window.rb +96 -0
  53. data/lib/rubik/orchestrator/shell_deps.rb +16 -0
  54. data/lib/rubik/orchestrator/step_executor.rb +2 -1
  55. data/lib/rubik/orchestrator/stream_manager.rb +2 -1
  56. data/lib/rubik/orchestrator/subagent/deferred_spec.rb +4 -1
  57. data/lib/rubik/orchestrator/subagent/instance.rb +7 -12
  58. data/lib/rubik/orchestrator/subagent/lifecycle.rb +3 -1
  59. data/lib/rubik/orchestrator/subagent/notices.rb +2 -2
  60. data/lib/rubik/orchestrator/subagent/questioner.rb +3 -1
  61. data/lib/rubik/orchestrator/subagent/reaper.rb +3 -5
  62. data/lib/rubik/orchestrator/subagent/resilience.rb +4 -2
  63. data/lib/rubik/orchestrator/subagent/result_archive.rb +0 -4
  64. data/lib/rubik/orchestrator/subagent/run_cycle.rb +2 -7
  65. data/lib/rubik/orchestrator/subagent/spawn_transaction.rb +11 -2
  66. data/lib/rubik/orchestrator/subagent/step_runner.rb +10 -2
  67. data/lib/rubik/orchestrator/subagent/transcript_formatter.rb +2 -1
  68. data/lib/rubik/orchestrator/subagent/type_definition.rb +0 -4
  69. data/lib/rubik/orchestrator/tool_timeout.rb +121 -1
  70. data/lib/rubik/platform/io_drain.rb +5 -2
  71. data/lib/rubik/platform/process.rb +144 -54
  72. data/lib/rubik/platform.rb +2 -1
  73. data/lib/rubik/plugin/manager.rb +2 -1
  74. data/lib/rubik/plugin/storage.rb +8 -8
  75. data/lib/rubik/repl/commands/agent_context.rb +8 -7
  76. data/lib/rubik/repl/commands/agent_execution.rb +13 -32
  77. data/lib/rubik/repl/commands/agent_models.rb +4 -3
  78. data/lib/rubik/repl/commands/agent_providers.rb +43 -2
  79. data/lib/rubik/repl/commands/base.rb +47 -2
  80. data/lib/rubik/repl/commands/buffer.rb +5 -4
  81. data/lib/rubik/repl/commands/lsp.rb +2 -1
  82. data/lib/rubik/repl/commands/pruner.rb +2 -1
  83. data/lib/rubik/repl/commands/secrets.rb +151 -0
  84. data/lib/rubik/repl/commands/workspace.rb +60 -150
  85. data/lib/rubik/repl/commands/workspace_approval.rb +209 -0
  86. data/lib/rubik/repl/config_wiring.rb +8 -6
  87. data/lib/rubik/repl/hooks.rb +2 -1
  88. data/lib/rubik/repl/input_execution.rb +162 -79
  89. data/lib/rubik/repl/input_loop.rb +2 -1
  90. data/lib/rubik/repl/lifecycle.rb +60 -210
  91. data/lib/rubik/repl/notice_router.rb +319 -0
  92. data/lib/rubik/repl/paste_support.rb +3 -1
  93. data/lib/rubik/repl/presentation.rb +5 -3
  94. data/lib/rubik/repl/pruner/gate.rb +3 -1
  95. data/lib/rubik/repl/pruner/harness.rb +2 -1
  96. data/lib/rubik/repl/shell.rb +4 -3
  97. data/lib/rubik/repl/tee_io.rb +2 -1
  98. data/lib/rubik/repl/turn_recorder.rb +6 -5
  99. data/lib/rubik/runtime/ast_service.rb +2 -1
  100. data/lib/rubik/runtime/discovery.rb +3 -2
  101. data/lib/rubik/runtime/loop_service.rb +4 -3
  102. data/lib/rubik/runtime/manifest_store.rb +9 -1
  103. data/lib/rubik/runtime/overlay_guard.rb +127 -0
  104. data/lib/rubik/runtime/overlay_storage.rb +109 -163
  105. data/lib/rubik/runtime/task_manager.rb +64 -25
  106. data/lib/rubik/sandbox/driver/docker.rb +5 -1
  107. data/lib/rubik/sandbox/runner.rb +21 -19
  108. data/lib/rubik/security/audit_log.rb +2 -1
  109. data/lib/rubik/security/command_gate.rb +126 -243
  110. data/lib/rubik/security/guard.rb +7 -3
  111. data/lib/rubik/security/secret_store.rb +492 -0
  112. data/lib/rubik/security/segment_report.rb +161 -0
  113. data/lib/rubik/security/synthesis_gate.rb +8 -11
  114. data/lib/rubik/session/manager.rb +7 -1
  115. data/lib/rubik/session/recorder.rb +2 -1
  116. data/lib/rubik/skills/manager.rb +4 -4
  117. data/lib/rubik/storage/search.rb +49 -0
  118. data/lib/rubik/storage/store.rb +13 -20
  119. data/lib/rubik/storage/transcript_indexer.rb +3 -2
  120. data/lib/rubik/storage/vakanuvis/harness.rb +2 -3
  121. data/lib/rubik/storage/vakanuvis.rb +2 -1
  122. data/lib/rubik/tools/base.rb +22 -0
  123. data/lib/rubik/tools/builtins/files.rb +3 -15
  124. data/lib/rubik/tools/builtins/goal_ledger.rb +12 -1
  125. data/lib/rubik/tools/builtins/grep.rb +1 -6
  126. data/lib/rubik/tools/builtins/lifecycle.rb +6 -5
  127. data/lib/rubik/tools/builtins/synthesis.rb +3 -3
  128. data/lib/rubik/tools/lifecycle_rollbacks.rb +14 -1
  129. data/lib/rubik/tools/preflight_runner.rb +2 -1
  130. data/lib/rubik/tools/truncator.rb +48 -36
  131. data/lib/rubik/tools/uri_resolver.rb +3 -2
  132. data/lib/rubik/ui/banner.rb +4 -3
  133. data/lib/rubik/ui/capability.rb +1 -0
  134. data/lib/rubik/ui/spinner.rb +3 -1
  135. data/lib/rubik/ui/statusline.rb +6 -5
  136. data/lib/rubik/version.rb +1 -1
  137. data/lib/rubik.rb +4 -5
  138. metadata +20 -1
@@ -0,0 +1,127 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../platform"
4
+ require_relative "../log"
5
+
6
+ module Rubik
7
+ module Runtime
8
+ # Guard/trust plane of the overlay storage (issue #447), single-homed here
9
+ # so Runtime::OverlayStorage stays the manifest/lifecycle coordinator:
10
+ #
11
+ # * Path containment: ensure_valid_overlay_dir! / ensure_contained_path! /
12
+ # safe_path_under? — the lexical + resolved containment policy over the
13
+ # overlay directories.
14
+ # * Trust/bootstrap screening: trust_mode?, bootstrap_opt_in? and
15
+ # screen_bootstrap_content — the fail-closed acceptance gate a sentinel
16
+ # file must pass before it is pinned into a manifest.
17
+ #
18
+ # Composition contract (the guard kwarg seam must keep working): the
19
+ # synthesis guard is NOT owned here — OverlayStorage forwards its own
20
+ # `guard:` kwarg at construction, so an injected guard (production: the
21
+ # service catalog's single operator-policy guard; tests: spies) is the
22
+ # one used, never bypassed. The lazy Rubik::Security::Guard default is
23
+ # deliberate (unchanged): overlay_storage.rb is a standalone-requireable
24
+ # file; security/guard loads only when screening actually happens, so no
25
+ # load-order audit is needed. Trust mode is likewise not re-read here:
26
+ # OverlayStorage injects the ManifestStore seam (issue #426) as a
27
+ # callable, so the plugin and overlay gates keep their single ENV read.
28
+ class OverlayGuard
29
+ # allowed_dirs: the [[overlay_dir, trusted_root], ...] table the storage
30
+ # derives from its own directory layout (it owns the layout; the guard
31
+ # owns the enforcement).
32
+ def initialize(allowed_dirs:, guard:, trust_mode:)
33
+ @allowed_dirs = allowed_dirs
34
+ @guard = guard
35
+ @trust_mode = trust_mode
36
+ end
37
+
38
+ # ── Path containment (moved verbatim from OverlayStorage, issue #447) ──
39
+
40
+ def ensure_valid_overlay_dir!(dir)
41
+ valid = @allowed_dirs.any? do |allowed_dir, trusted_root|
42
+ Platform.path_equal?(dir, allowed_dir) && Platform.resolved_path_under?(dir, trusted_root)
43
+ end
44
+ return if valid
45
+
46
+ raise ArgumentError, "Invalid overlay directory: #{dir}"
47
+ end
48
+
49
+ def ensure_contained_path!(path, parent_dir)
50
+ raise ArgumentError, "Path traversal attempt detected: #{path}" unless safe_path_under?(path, parent_dir)
51
+ end
52
+
53
+ def safe_path_under?(path, parent_dir)
54
+ return false if path.nil? || parent_dir.nil?
55
+
56
+ ensure_valid_overlay_dir!(parent_dir)
57
+
58
+ # Lexical containment check first
59
+ return false unless Platform.path_under?(path, parent_dir)
60
+
61
+ # If path exists or parent exists, also check resolved path containment
62
+ return Platform.resolved_path_under?(path, parent_dir) if File.exist?(path) || File.exist?(parent_dir)
63
+
64
+ true
65
+ rescue StandardError
66
+ false
67
+ end
68
+
69
+ # ── Trust / bootstrap screening (moved verbatim from OverlayStorage, issue #447) ──
70
+
71
+ # Ortak kaçış kapısı predicate'i: iki güvenlik kapısının (verify_integrity,
72
+ # verified_dir_entries) kopya ENV kontrolüyle sürünerek ayrışmasını engeller.
73
+ # Tek seam ManifestStore'da yaşar (issue #426); plugin tarafı da aynı kapıdan geçer.
74
+ def trust_mode?
75
+ @trust_mode.call
76
+ end
77
+
78
+ # İlk-bootstrap açık rızası: manifest'siz dizindeki sentinel dosyaların ilk taramada
79
+ # kabul edilmesi ancak bu env ile mümkündür (kayıt kalıcıdır; sonraki açılışlar env'siz çalışır).
80
+ def bootstrap_opt_in?
81
+ ENV["RUBIK_BOOTSTRAP_OVERLAYS"] == "1"
82
+ end
83
+
84
+ # Aday 07'den ertelenen güvenlik kalemi: manifestsız dizindeki sentinel
85
+ # dosya manifest'e yazılmadan önce synthesis guard'ından geçirilir.
86
+ # Reddedilen (veya taranamayan) dosya manifest'e YAZILMAZ — sonraki tarama
87
+ # yeniden tarar ve reddeder (sessiz heal, bozuk-manifest doktriniyle
88
+ # çelişir); load_all/load_tools'un mevcut :rejected atlaması devreye girer.
89
+ # Parse hatası guard içinde yutulur (çalıştırılamaz kod güvenlik olayı
90
+ # değil); guard'ın kendisi patlarsa da dosya fail-closed reddedilir —
91
+ # SystemStackError dahil: rakip içerikte derin yuvalama AST walk'ı
92
+ # taşırebilir, tek dosyanın reddiyesi tüm taramayı çökertmemeli.
93
+ # Bilinçli asimetri: dosyanın TAMAMI (Description/Schema başlığı dahil)
94
+ # taranır — sentez anında yalnızca kod taranıyordu. Kabul kapısı daha
95
+ # sıkı olmak güvenli yöndür; başlık metnine denk gelen nadir yanlış
96
+ # pozitif dosyayı makinede yeniden kayıtla çözülür.
97
+ # Emit doktrini (guard.rb run_synthesis_gate hükmü): güvenlik kararının
98
+ # tek kullanıcı-yüzü izi Log.warn ile yazılır — $VERBOSE=nil altında da
99
+ # yaşar (Log.emit $stderr.puts kullanır, Kernel#warn değil) ve varsayılan
100
+ # RUBIK_LOG_LEVEL=warn'da her zaman basılır (issue #452).
101
+ def screen_bootstrap_content(content, basename)
102
+ bootstrap_guard.verify_synthesis_safety!(content)
103
+ :ok
104
+ rescue Rubik::Security::BlockedWriteError => e
105
+ Rubik::Log.warn(:security, "[SECURITY] Bootstrap overlay '#{basename}' refused by synthesis guard: #{e.message}")
106
+ :rejected
107
+ rescue StandardError, ScriptError, SystemStackError => e
108
+ Rubik::Log.warn(:security, "[SECURITY] Bootstrap overlay '#{basename}' could not be screened (#{e.class}: #{e.message}); refusing.")
109
+ :rejected
110
+ end
111
+
112
+ private
113
+
114
+ # Bootstrap kabul taramasında kullanılacak guard: kwarg'la geçilen örnek
115
+ # (üretimde service catalog'un tek operatör-policy guard'ı) ya da lazy
116
+ # default. Lazy çözüm bilinçli: overlay_storage.rb standalone require
117
+ # edilebilen bir dosyadır; security/guard yalnızca tarama gerçekten
118
+ # gerektiğinde yüklenir, load-order denetimi gerekmez.
119
+ def bootstrap_guard
120
+ @bootstrap_guard ||= begin
121
+ require_relative "../security/guard"
122
+ @guard || Rubik::Security::Guard.new
123
+ end
124
+ end
125
+ end
126
+ end
127
+ end
@@ -6,14 +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"
10
12
  require_relative "../plugin/package_inventory"
11
13
  require_relative "synthesized_command_context"
12
14
  require_relative "synthesized_tool_context"
15
+ require_relative "overlay_guard"
13
16
 
14
17
  module Rubik
15
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).
16
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
+
17
32
  attr_reader :root_dir, :home_dir
18
33
 
19
34
  COMMAND_SENTINEL = "# Rubik Custom Command:"
@@ -22,9 +37,16 @@ module Rubik
22
37
  def initialize(root_dir: Dir.pwd, home_dir: ENV.fetch("HOME", nil), guard: nil, runtime_manager: nil, runtime_context: nil)
23
38
  @root_dir = File.expand_path(root_dir)
24
39
  @home_dir = File.expand_path(home_dir || ENV["HOME"] || ".")
25
- @guard = guard
26
40
  @runtime_manager = runtime_manager
27
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? })
28
50
  ensure_directories
29
51
  end
30
52
 
@@ -32,8 +54,8 @@ module Rubik
32
54
  # store wires the overlay-dir validation + containment checks into it.
33
55
  def manifest_store
34
56
  @manifest_store ||= ManifestStore.new(validate_path: lambda { |path, dir|
35
- ensure_valid_overlay_dir!(dir)
36
- ensure_contained_path!(path, dir)
57
+ @overlay_guard.ensure_valid_overlay_dir!(dir)
58
+ @overlay_guard.ensure_contained_path!(path, dir)
37
59
  })
38
60
  end
39
61
 
@@ -57,7 +79,7 @@ module Rubik
57
79
  [project_commands_dir, global_commands_dir, project_tools_dir, global_tools_dir].each do |dir|
58
80
  FileUtils.mkdir_p(dir)
59
81
  rescue SystemCallError => e
60
- warn "[WARN] Failed to create overlay directory #{dir}: #{e.message}" if ENV["RUBIK_DEBUG"]
82
+ Rubik::Log.warn(:overlay, "[WARN] Failed to create overlay directory #{dir}: #{e.message}") if ENV["RUBIK_DEBUG"]
61
83
  end
62
84
  end
63
85
 
@@ -81,16 +103,16 @@ module Rubik
81
103
  refuse_corrupt_manifest!(dir, :record, filename)
82
104
 
83
105
  path = File.join(dir, filename)
84
- ensure_contained_path!(path, dir)
106
+ @overlay_guard.ensure_contained_path!(path, dir)
85
107
  hash = Digest::SHA256.hexdigest(normalize_content(File.binread(path)))
86
108
  manifest_store.record_hash(dir, filename, hash, scope: scope)
87
109
  end
88
110
 
89
111
  def verify_integrity(file_path, dir, bootstrap_eligible: false)
90
- return :trusted if trust_mode?
112
+ return :trusted if @overlay_guard.trust_mode?
91
113
 
92
- unless safe_path_under?(file_path, dir)
93
- warn "[SECURITY] Path traversal attempt detected for overlay '#{file_path}'. Skipping."
114
+ unless @overlay_guard.safe_path_under?(file_path, dir)
115
+ Rubik::Log.warn(:overlay, "[SECURITY] Path traversal attempt detected for overlay '#{file_path}'. Skipping.")
94
116
  return :rejected
95
117
  end
96
118
 
@@ -106,8 +128,8 @@ module Rubik
106
128
  # Constant-time comparison policy is single-homed in ManifestStore
107
129
  # (issue #426), same as plugin verification.
108
130
  expected_hash = manifest[basename]["sha256"]
109
- warn "[SECURITY] Integrity check failed for overlay '#{basename}': file modified " \
110
- "since synthesis. Skipping. (expected: #{expected_hash}, got: #{current_hash})"
131
+ Rubik::Log.warn(:overlay, "[SECURITY] Integrity check failed for overlay '#{basename}': file modified " \
132
+ "since synthesis. Skipping. (expected: #{expected_hash}, got: #{current_hash})")
111
133
  :rejected
112
134
  when :unknown
113
135
  if bootstrap_eligible && sentinel_content?(current_content)
@@ -116,7 +138,7 @@ module Rubik
116
138
  # verified_dir_entries taramanın başında verir. Manifest varken bootstrap asla çalışmaz.
117
139
  # Kabul ÖNCE synthesis guard'ından geçer (Aday 07 ertelemesi): klonlanan depodaki
118
140
  # dosya bu ortamda sentezlenmemişti; reddedilen dosya manifest'e yazılmaz.
119
- verdict = screen_bootstrap_content(current_content, basename)
141
+ verdict = @overlay_guard.screen_bootstrap_content(current_content, basename)
120
142
  return verdict unless verdict == :ok
121
143
 
122
144
  scope_match = current_content.match(/# Scope:\s*(.*)/)
@@ -130,7 +152,7 @@ module Rubik
130
152
  save_manifest(dir, manifest)
131
153
  :bootstrapped
132
154
  else
133
- warn "[SECURITY] Unknown overlay file '#{basename}' not in manifest. Skipping."
155
+ Rubik::Log.warn(:overlay, "[SECURITY] Unknown overlay file '#{basename}' not in manifest. Skipping.")
134
156
  :rejected
135
157
  end
136
158
  end
@@ -138,7 +160,7 @@ module Rubik
138
160
 
139
161
  # Issue #407: the command/tool quadruplets collapse onto shared skeletons
140
162
  # (save / delete / load_entries in the private section) behind the Kind
141
- # adapter at the bottom of this file. Public surface unchanged: these
163
+ # adapter at the bottom of this class. Public surface unchanged: these
142
164
  # delegators keep the exact pre-refactor signatures and per-kind defaults.
143
165
  def save_command(name, code, scope: :project, description: "Custom command")
144
166
  save(COMMAND_KIND, name, code, scope: scope, description: description)
@@ -186,7 +208,7 @@ module Rubik
186
208
  if proc_handler.arity == 1
187
209
  proc_handler.call(args)
188
210
  elsif proc_handler.arity == 2
189
- warn "[rubik] overlay command invoked without a dispatch CommandContext" unless ctx || ENV["RUBIK_TEST"]
211
+ Rubik::Log.warn(:overlay, "[rubik] overlay command invoked without a dispatch CommandContext") unless ctx || ENV["RUBIK_TEST"]
190
212
  sealed_ctx = if ctx.is_a?(Rubik::REPL::SynthesizedCommandContext)
191
213
  ctx
192
214
  else
@@ -223,7 +245,7 @@ module Rubik
223
245
  out_ctx = if ctx
224
246
  ctx
225
247
  elsif shell.respond_to?(:command_context)
226
- warn "[rubik] overlay command invoked without a dispatch CommandContext" unless ENV["RUBIK_TEST"]
248
+ Rubik::Log.warn(:overlay, "[rubik] overlay command invoked without a dispatch CommandContext") unless ENV["RUBIK_TEST"]
227
249
  shell.command_context
228
250
  else
229
251
  shell.output
@@ -233,7 +255,7 @@ module Rubik
233
255
  end
234
256
  # register_command, built-in çakışmasında sessizce false döner; red,
235
257
  # load_all'un [OVERLAY] yoluna düşsün ve loaded listesi doğru kalsın.
236
- 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
237
259
  end
238
260
 
239
261
  def save_tool(name, code, scope: :project, description: "Custom native tool", params_schema: nil, risk: :execute)
@@ -270,7 +292,7 @@ module Rubik
270
292
  # A malformed schema silently claiming "no arguments"
271
293
  # hides real overlay bugs; keep loading (the tool is
272
294
  # hash-verified) but say so.
273
- warn "[rubik] overlay tool '#{name}' has a malformed '# Schema:' header; treating as no-arg schema"
295
+ Rubik::Log.warn(:overlay, "[rubik] overlay tool '#{name}' has a malformed '# Schema:' header; treating as no-arg schema")
274
296
  {}
275
297
  end
276
298
  else
@@ -313,8 +335,64 @@ module Rubik
313
335
  end
314
336
  end
315
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
+
316
382
  private
317
383
 
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
+ [
389
+ [project_commands_dir, @root_dir],
390
+ [global_commands_dir, @home_dir],
391
+ [project_tools_dir, @root_dir],
392
+ [global_tools_dir, @home_dir]
393
+ ].freeze
394
+ end
395
+
318
396
  # Single home of the fail-closed corrupt-manifest contract (issue #407,
319
397
  # single-homed in ManifestStore by issue #426): record_hash and the
320
398
  # delete skeleton refuse through this one raise. `verb` reproduces the
@@ -336,7 +414,7 @@ module Rubik
336
414
 
337
415
  filename = kind.filename_for(clean_name)
338
416
  file_path = File.join(target_dir, filename)
339
- ensure_contained_path!(file_path, target_dir)
417
+ @overlay_guard.ensure_contained_path!(file_path, target_dir)
340
418
 
341
419
  header = kind.header_lines(name: clean_name, scope: scope, description: description,
342
420
  risk: risk, schema: params_schema ? JSON.dump(params_schema) : "{}")
@@ -345,7 +423,7 @@ module Rubik
345
423
  { ok: true, path: file_path, name: clean_name, scope: scope }
346
424
  rescue StandardError => e
347
425
  # 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"]
426
+ Rubik::Log.warn(:overlay, "[WARN] [OVERLAY] Failed to save #{kind.label} '#{name}' to #{file_path}: #{e.class}: #{e.message}") if kind.debug_warn && ENV["RUBIK_DEBUG"]
349
427
  { ok: false, error: e.message }
350
428
  end
351
429
 
@@ -358,7 +436,7 @@ module Rubik
358
436
  target_dir = kind_dir(kind, scope)
359
437
  filename = kind.filename_for(clean_name)
360
438
  file_path = File.join(target_dir, filename)
361
- ensure_contained_path!(file_path, target_dir)
439
+ @overlay_guard.ensure_contained_path!(file_path, target_dir)
362
440
 
363
441
  refuse_corrupt_manifest!(target_dir, :delete, filename)
364
442
 
@@ -387,15 +465,15 @@ module Rubik
387
465
  file_path = meta[:path]
388
466
  target_dir = kind_dir(kind, meta[:scope])
389
467
 
390
- ensure_contained_path!(file_path, target_dir)
468
+ @overlay_guard.ensure_contained_path!(file_path, target_dir)
391
469
  code = File.read(file_path)
392
470
  if yield(name, code, meta[:scope])
393
471
  loaded << name
394
472
  elsif kind.warn_on_unusable
395
- warn "[OVERLAY] Custom #{kind.label} '#{name}' from #{file_path} did not evaluate to a usable tool."
473
+ Rubik::Log.warn(:overlay, "[OVERLAY] Custom #{kind.label} '#{name}' from #{file_path} did not evaluate to a usable tool.")
396
474
  end
397
475
  rescue StandardError => e
398
- warn "[OVERLAY] Failed to load custom #{kind.label} '#{name}' from #{file_path}: #{e.class}: #{e.message}"
476
+ Rubik::Log.warn(:overlay, "[OVERLAY] Failed to load custom #{kind.label} '#{name}' from #{file_path}: #{e.class}: #{e.message}")
399
477
  end
400
478
  loaded
401
479
  end
@@ -420,86 +498,6 @@ module Rubik
420
498
  scope.to_sym == :global ? public_send(kind.global_dir) : public_send(kind.project_dir)
421
499
  end
422
500
 
423
- def ensure_valid_overlay_dir!(dir)
424
- allowed = [
425
- [project_commands_dir, @root_dir],
426
- [global_commands_dir, @home_dir],
427
- [project_tools_dir, @root_dir],
428
- [global_tools_dir, @home_dir]
429
- ]
430
- valid = allowed.any? do |allowed_dir, trusted_root|
431
- Platform.path_equal?(dir, allowed_dir) && Platform.resolved_path_under?(dir, trusted_root)
432
- end
433
- return if valid
434
-
435
- raise ArgumentError, "Invalid overlay directory: #{dir}"
436
- end
437
-
438
- def ensure_contained_path!(path, parent_dir)
439
- raise ArgumentError, "Path traversal attempt detected: #{path}" unless safe_path_under?(path, parent_dir)
440
- end
441
-
442
- def safe_path_under?(path, parent_dir)
443
- return false if path.nil? || parent_dir.nil?
444
-
445
- ensure_valid_overlay_dir!(parent_dir)
446
-
447
- # Lexical containment check first
448
- return false unless Platform.path_under?(path, parent_dir)
449
-
450
- # If path exists or parent exists, also check resolved path containment
451
- return Platform.resolved_path_under?(path, parent_dir) if File.exist?(path) || File.exist?(parent_dir)
452
-
453
- true
454
- rescue StandardError
455
- false
456
- end
457
-
458
- # Bootstrap kabul taramasında kullanılacak guard: kwarg'la geçilen örnek
459
- # (üretimde service catalog'un tek operatör-policy guard'ı) ya da lazy
460
- # default. Lazy çözüm bilinçli: overlay_storage.rb standalone require
461
- # edilebilen bir dosyadır; security/guard yalnızca tarama gerçekten
462
- # gerektiğinde yüklenir, load-order denetimi gerekmez.
463
- def bootstrap_guard
464
- @bootstrap_guard ||= begin
465
- require_relative "../security/guard"
466
- @guard || Rubik::Security::Guard.new
467
- end
468
- end
469
-
470
- # Aday 07'den ertelenen güvenlik kalemi: manifestsız dizindeki sentinel
471
- # dosya manifest'e yazılmadan önce synthesis guard'ından geçirilir.
472
- # Reddedilen (veya taranamayan) dosya manifest'e YAZILMAZ — sonraki tarama
473
- # yeniden tarar ve reddeder (sessiz heal, bozuk-manifest doktriniyle
474
- # çelişir); load_all/load_tools'un mevcut :rejected atlaması devreye girer.
475
- # Parse hatası guard içinde yutulur (çalıştırılamaz kod güvenlik olayı
476
- # değil); guard'ın kendisi patlarsa da dosya fail-closed reddedilir —
477
- # SystemStackError dahil: rakip içerikte derin yuvalama AST walk'ı
478
- # taşırebilir, tek dosyanın reddiyesi tüm taramayı çökertmemeli.
479
- # Bilinçli asimetri: dosyanın TAMAMI (Description/Schema başlığı dahil)
480
- # taranır — sentez anında yalnızca kod taranıyordu. Kabul kapısı daha
481
- # sıkı olmak güvenli yöndür; başlık metnine denk gelen nadir yanlış
482
- # pozitif dosyayı makinede yeniden kayıtla çözülür.
483
- # Emit doktrini (guard.rb run_synthesis_gate hükmü): güvenlik kararının
484
- # tek kullanıcı-yüzü izi $VERBOSE=nil altında da yaşamalıdır — $stderr.puts.
485
- def screen_bootstrap_content(content, basename)
486
- bootstrap_guard.verify_synthesis_safety!(content)
487
- :ok
488
- rescue Rubik::Security::BlockedWriteError => e
489
- $stderr.puts "[SECURITY] Bootstrap overlay '#{basename}' refused by synthesis guard: #{e.message}" # rubocop:disable Style/StderrPuts
490
- :rejected
491
- rescue StandardError, ScriptError, SystemStackError => e
492
- $stderr.puts "[SECURITY] Bootstrap overlay '#{basename}' could not be screened (#{e.class}: #{e.message}); refusing." # rubocop:disable Style/StderrPuts
493
- :rejected
494
- end
495
-
496
- # Ortak kaçış kapısı predicate'i: iki güvenlik kapısının (verify_integrity,
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.
499
- def trust_mode?
500
- manifest_store.trust_mode?
501
- end
502
-
503
501
  # Üç durumlu manifest yoklaması ve bozuk-manifest reddi ManifestStore'da
504
502
  # tek home'da (issue #426): kayıt yolu (record_hash) ve delete iskeleti
505
503
  # bozuk manifestte {} davranışına değil, fail-closed redde bağlı.
@@ -514,14 +512,14 @@ module Rubik
514
512
  files = Dir.glob(File.join(dir, "*.rb"))
515
513
 
516
514
  # Kaçış kapısı: trust modu manifest durumundan bağımsız olarak tüm dosyaları güvenilir sayar.
517
- 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?
518
516
 
519
517
  case manifest_state(dir)
520
518
  when :corrupt
521
- warn "[SECURITY] Corrupt manifest in #{dir}; skipping #{files.size} overlay(s)."
519
+ Rubik::Log.warn(:overlay, "[SECURITY] Corrupt manifest in #{dir}; skipping #{files.size} overlay(s).")
522
520
  []
523
521
  when :missing
524
- if bootstrap_opt_in?
522
+ if @overlay_guard.bootstrap_opt_in?
525
523
  bootstrapped = 0
526
524
  entries = files.map do |f|
527
525
  integrity = verify_integrity(f, dir, bootstrap_eligible: true)
@@ -529,8 +527,8 @@ module Rubik
529
527
  { name: File.basename(f, ".rb"), scope: scope, path: f, integrity: integrity }
530
528
  end
531
529
  if bootstrapped.positive?
532
- warn "[BOOTSTRAP] First scan of #{dir}: recorded #{bootstrapped} overlay(s) into .manifest.json; " \
533
- "unknown files will be rejected from now on."
530
+ Rubik::Log.warn(:overlay, "[BOOTSTRAP] First scan of #{dir}: recorded #{bootstrapped} overlay(s) into .manifest.json; " \
531
+ "unknown files will be rejected from now on.")
534
532
  end
535
533
  entries
536
534
  else
@@ -538,8 +536,8 @@ module Rubik
538
536
  # sentinel dosyalar görünür tek satırlık bildirimle atlanır.
539
537
  gated = files.count { |f| sentinel_file?(f) }
540
538
  if gated.positive?
541
- warn "[BOOTSTRAP] #{gated} unrecorded sentinel overlay(s) in #{dir} were skipped; " \
542
- "first-time acceptance requires RUBIK_BOOTSTRAP_OVERLAYS=1."
539
+ Rubik::Log.warn(:overlay, "[BOOTSTRAP] #{gated} unrecorded sentinel overlay(s) in #{dir} were skipped; " \
540
+ "first-time acceptance requires RUBIK_BOOTSTRAP_OVERLAYS=1.")
543
541
  end
544
542
  files.map { |f| { name: File.basename(f, ".rb"), scope: scope, path: f, integrity: verify_integrity(f, dir) } }
545
543
  end
@@ -548,12 +546,6 @@ module Rubik
548
546
  end
549
547
  end
550
548
 
551
- # İlk-bootstrap açık rızası: manifest'siz dizindeki sentinel dosyaların ilk taramada
552
- # kabul edilmesi ancak bu env ile mümkündür (kayıt kalıcıdır; sonraki açılışlar env'siz çalışır).
553
- def bootstrap_opt_in?
554
- ENV["RUBIK_BOOTSTRAP_OVERLAYS"] == "1"
555
- end
556
-
557
549
  def sentinel_content?(content)
558
550
  content.include?(COMMAND_SENTINEL) || content.include?(TOOL_SENTINEL)
559
551
  end
@@ -562,7 +554,7 @@ module Rubik
562
554
  File.file?(path) && sentinel_content?(File.binread(path))
563
555
  rescue StandardError => e
564
556
  # Audit 1: unreadable => fail-closed (not a sentinel), but traceable.
565
- warn "[WARN] [OVERLAY] sentinel check failed for #{path}: #{e.class}: #{e.message}" if ENV["RUBIK_DEBUG"]
557
+ Rubik::Log.warn(:overlay, "[WARN] [OVERLAY] sentinel check failed for #{path}: #{e.class}: #{e.message}") if ENV["RUBIK_DEBUG"]
566
558
  false
567
559
  end
568
560
 
@@ -570,51 +562,5 @@ module Rubik
570
562
  Object.new.instance_eval { binding }
571
563
  end
572
564
  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
619
565
  end
620
566
  end