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
@@ -0,0 +1,143 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "join"
4
+
5
+ module Rubik
6
+ module Concurrency
7
+ # Single home of the bounded-queue worker skeleton shared by the pruner
8
+ # and vakanuvis harnesses: one worker thread drains a bounded FIFO until
9
+ # a STOP marker, with atomic admission (stopped-check + push share one
10
+ # monitor critical section), idempotent shutdown, busy accounting and a
11
+ # last-ditch dispatch net. Mechanics only, per the join.rb contract: the
12
+ # host keeps its own monitor and log channel — the skeleton never
13
+ # allocates a lock and never logs directly.
14
+ #
15
+ # Host contract — state (host-initialized, skeleton-operated):
16
+ # @monitor / @queue / @worker — host-owned; domain state shares the monitor
17
+ # @stopped / @busy — skeleton-owned flags under @monitor
18
+ # plus private hooks: worker_max_queue (FIFO bound), worker_warn (log
19
+ # sink), worker_drop_accounted (overflow reconciliation),
20
+ # worker_dispatch_failed (net: receives kind, payload, error so the
21
+ # host reconciles its accounting), worker_before_join
22
+ # (pre-join teardown, default none) and handle_event (dispatch hook).
23
+ module Worker
24
+ # Queue terminator; drop-oldest must never swallow it (the worker would drain forever).
25
+ STOP = :__worker_stop__
26
+
27
+ # Shutdown grants the worker JOIN_TIMEOUT seconds to drain; the idle
28
+ # probe polls at a cadence that keeps teardown feeling immediate.
29
+ JOIN_TIMEOUT = 2
30
+ IDLE_POLL = 0.01
31
+
32
+ def stopped? = @monitor.synchronize { @stopped }
33
+
34
+ # Queue + in-flight count: incremented at admission, decremented when
35
+ # consumed or dropped — closes the accounting window pop would open.
36
+ def busy? = @monitor.synchronize { @busy.positive? }
37
+
38
+ def queue_size = @queue.size
39
+
40
+ # Idle probe: Join's mechanics are handle-shaped (join a thread), this
41
+ # is predicate-shaped (poll busy?) — same deadline discipline, own loop.
42
+ def wait_idle(timeout: 2.0)
43
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout
44
+ sleep IDLE_POLL while busy? && Process.clock_gettime(Process::CLOCK_MONOTONIC) < deadline
45
+ !busy?
46
+ end
47
+
48
+ def shutdown
49
+ @monitor.synchronize do
50
+ return if @stopped
51
+
52
+ @stopped = true
53
+ @busy += 1 # the STOP marker counts as consumed work
54
+ @queue.push(STOP)
55
+ end
56
+ worker_before_join
57
+ outcome = Join.thread(@worker, timeout: JOIN_TIMEOUT)
58
+ if outcome == :timeout
59
+ # Thread#kill waits out the dying thread's unwind, so the in-flight
60
+ # ensure decrement runs before we return; busy then equals the
61
+ # unconsumed queue — lost work stays honestly counted (-1: the
62
+ # STOP marker itself is still queued).
63
+ worker_warn("worker did not stop in #{JOIN_TIMEOUT}s — killing with #{queue_size - 1} event(s) unprocessed")
64
+ @worker.kill
65
+ elsif outcome.is_a?(StandardError)
66
+ # Error-as-data: Join returns a dead-with-exception thread's error
67
+ # — teardown completes, the death is reported, never swallowed.
68
+ worker_warn("worker thread died: #{outcome.class}: #{outcome.message}")
69
+ end
70
+ @worker = nil
71
+ end
72
+
73
+ # Atomic admission: the stopped-check and the push share one critical
74
+ # section — an event racing shutdown either lands before STOP (and is
75
+ # consumed) or is refused; it can never straddle the marker and leak a
76
+ # busy increment behind an unconsumable item. The overflow hook fires
77
+ # OUTSIDE the monitor: a slow host reconcile (gate locks, log I/O) must
78
+ # never stall admission, shutdown or wait_idle.
79
+ def enqueue_event(kind, payload)
80
+ dropped = nil
81
+ @monitor.synchronize do
82
+ return false if @stopped
83
+
84
+ if @queue.size >= worker_max_queue
85
+ dropped = drop_oldest!
86
+ return false if dropped == STOP
87
+ end
88
+ @busy += 1
89
+ @queue.push([kind, payload])
90
+ end
91
+ worker_drop_accounted(dropped) if dropped
92
+ true
93
+ end
94
+
95
+ private
96
+
97
+ def worker_before_join; end
98
+
99
+ def run_worker
100
+ loop do
101
+ kind, payload = @queue.pop
102
+ break if kind == STOP
103
+
104
+ handle_event(kind, payload)
105
+ rescue StandardError => e
106
+ # A raise escaping handle_event's own rescue would kill the worker
107
+ # with queued events unconsumed; hand the item to the hook (the
108
+ # host reconciles its accounting) and keep draining. The net is
109
+ # itself guarded: when it runs, log/reconcile infrastructure is
110
+ # already failing and a second raise must not kill the worker.
111
+ begin
112
+ worker_dispatch_failed(kind, payload, e)
113
+ rescue StandardError
114
+ nil
115
+ end
116
+ ensure
117
+ @monitor.synchronize { @busy -= 1 }
118
+ end
119
+ end
120
+
121
+ # Make room for one admission (assumes @monitor held): pops the oldest
122
+ # item, decrements its busy increment, and returns it for the caller to
123
+ # hand to worker_drop_accounted outside the monitor. Returns STOP
124
+ # (marker re-pushed; the caller refuses rather than strand an event
125
+ # behind the terminator) or nil when the worker drained the queue
126
+ # between the size check and this pop (nothing dropped, unaccounted).
127
+ def drop_oldest!
128
+ item = @queue.pop(true)
129
+ if item == STOP
130
+ @queue.push(STOP)
131
+ return STOP
132
+ end
133
+
134
+ @busy -= 1
135
+ item
136
+ rescue ThreadError
137
+ # Worker drained between the size check and pop(true): no-op race
138
+ # loss — nothing was dropped, nothing to account.
139
+ nil
140
+ end
141
+ end
142
+ end
143
+ end
@@ -6,6 +6,7 @@ require_relative "concurrency/event_loop"
6
6
  require_relative "concurrency/scheduler"
7
7
  require_relative "concurrency/boundary"
8
8
  require_relative "concurrency/join"
9
+ require_relative "concurrency/worker"
9
10
  require_relative "concurrency/fiber_timeout"
10
11
 
11
12
  module Rubik
@@ -3,6 +3,10 @@
3
3
  module Rubik
4
4
  class Config
5
5
  module DeepOps
6
+ SENSITIVE_PROJECT_CONFIG_KEYS = [
7
+ "security", "sandbox", "plugins", "mcp", "lsp", "project", "test", "linter", "adapter"
8
+ ].freeze
9
+
6
10
  private
7
11
 
8
12
  def deep_dup(obj)
@@ -89,6 +93,19 @@ module Rubik
89
93
  end
90
94
  target[last_key] = value
91
95
  end
96
+
97
+ def filter_untrusted_project_config(hash)
98
+ return hash unless hash.is_a?(Hash)
99
+
100
+ filtered = deep_dup(hash)
101
+ SENSITIVE_PROJECT_CONFIG_KEYS.each { |key| filtered.delete(key) }
102
+ if filtered["workspace"].is_a?(Hash)
103
+ ["allow_external_writes", "allowed_external_dirs", "additional_roots"].each do |k|
104
+ filtered["workspace"].delete(k)
105
+ end
106
+ end
107
+ filtered
108
+ end
92
109
  end
93
110
  end
94
111
  end
@@ -72,7 +72,6 @@ module Rubik
72
72
  "command_allowlist" => [], # operator-managed token-prefix entries (e.g. "node .gitnexus/run.cjs")
73
73
  "allow_safe_probes" => true # `bash --version`-style version/help probes bypass the blocklist
74
74
  },
75
- "network" => { "allow" => false },
76
75
  "buffer" => {
77
76
  "auto_apply" => "manual",
78
77
  "model_can_apply" => true,
@@ -220,6 +219,12 @@ module Rubik
220
219
  "adapter" => {}
221
220
  }.freeze
222
221
 
222
+ # Retired config keys (dotted key => guidance): validate_schema emits the
223
+ # tailored deprecation at boot; runtime set() keeps its own warn (config_wiring.rb).
224
+ RETIRED_KEYS = {
225
+ "network.allow" => "[DEPRECATION] Config key 'network.allow' is deprecated and has no effect. Use 'sandbox.allow_network' instead."
226
+ }.freeze
227
+
223
228
  private
224
229
 
225
230
  # Schema-backed keys must satisfy their spec wherever the merged tree is validated.
@@ -245,6 +250,8 @@ module Rubik
245
250
  else
246
251
  "Unknown config key '#{current_key}'."
247
252
  end
253
+ # A retired key wins over the generic/fuzzy unknown-key line.
254
+ suggestion_msg = retired_key_warning(current_key, val) || suggestion_msg
248
255
 
249
256
  raise ArgumentError, suggestion_msg if strict
250
257
 
@@ -254,6 +261,21 @@ module Rubik
254
261
  end
255
262
  end
256
263
  end
264
+
265
+ # Tailored deprecation for a retired key (RETIRED_KEYS): an exact dotted
266
+ # hit, or a config-file section whose subtree carries a retired leaf
267
+ # ("network: {allow: true}" lands on unknown top-level 'network').
268
+ # nil falls through to the generic unknown-key line.
269
+ def retired_key_warning(current_key, val)
270
+ return RETIRED_KEYS[current_key] if RETIRED_KEYS.key?(current_key)
271
+
272
+ return nil unless val.is_a?(Hash)
273
+
274
+ retired_leaves = val.keys.filter_map { |child| RETIRED_KEYS["#{current_key}.#{child}"] }
275
+ return nil if retired_leaves.empty?
276
+
277
+ retired_leaves.join(" ")
278
+ end
257
279
  end
258
280
  end
259
281
  end
@@ -41,7 +41,6 @@ module Rubik
41
41
  "sandbox.shell" => { type: :enum, allowed: ["auto", "bash", "powershell"] },
42
42
  "security.allow_safe_probes" => { type: :boolean },
43
43
  "security.command_allowlist" => { type: :array },
44
- "network.allow" => { type: :boolean },
45
44
  "buffer.auto_apply" => { type: :enum, allowed: ["manual", "on_test", "on_finish", "always"] },
46
45
  "buffer.model_can_apply" => { type: :boolean },
47
46
  "buffer.prompt_indicator" => { type: :boolean },
@@ -67,6 +67,7 @@ module Rubik
67
67
  nil
68
68
  end
69
69
  store = store_for(scope_sym)
70
+ ensure_owner_only!(target_path)
70
71
 
71
72
  validation_error = nil
72
73
  store.transaction do
@@ -136,6 +137,19 @@ module Rubik
136
137
 
137
138
  private
138
139
 
140
+ # Provider api_key values persist in these stores, so the file must be
141
+ # owner-only from the first byte on disk. YAML::Store creates a missing
142
+ # file with the process umask (typically 0644); pre-creating at 0600
143
+ # closes the window before the first transaction opens it. A chmod
144
+ # failure keeps the legacy best-effort behavior instead of failing the
145
+ # save.
146
+ def ensure_owner_only!(path)
147
+ FileUtils.touch(path) unless File.exist?(path)
148
+ File.chmod(0o600, path)
149
+ rescue SystemCallError
150
+ nil
151
+ end
152
+
139
153
  def ensure_rubik_directories
140
154
  rubik_home = File.join(@home_dir, ".rubik")
141
155
  ["snapshots", "sessions", "commands", "tools"].each do |sub|
data/lib/rubik/config.rb CHANGED
@@ -18,6 +18,7 @@ module Rubik
18
18
  include ModelCatalog
19
19
 
20
20
  DEFAULT_CONFIG = Defaults::DEFAULT_CONFIG
21
+ SENSITIVE_PROJECT_CONFIG_KEYS = DeepOps::SENSITIVE_PROJECT_CONFIG_KEYS
21
22
 
22
23
  attr_reader :data, :warnings, :root_dir, :home_dir,
23
24
  :defaults_layer, :global_layer, :project_layer, :env_layer, :session_layer
@@ -34,9 +35,7 @@ module Rubik
34
35
  @event_bus = nil
35
36
  @session_layer = {}
36
37
  @defaults_layer = deep_dup(DEFAULT_CONFIG)
37
- @global_layer = {}
38
- @project_layer = {}
39
- @env_layer = {}
38
+ @global_layer = @project_layer = @env_layer = {}
40
39
  ensure_rubik_directories
41
40
  @data = load_merged_config
42
41
  end
@@ -283,6 +282,11 @@ module Rubik
283
282
  @global_layer = {} unless @global_layer.is_a?(Hash)
284
283
  @project_layer = load_yaml(project_config_path)
285
284
  @project_layer = {} unless @project_layer.is_a?(Hash)
285
+
286
+ if @project_layer.any? && defined?(Rubik::CLI::WorkspaceTrust) && !Rubik::CLI::WorkspaceTrust.trusted?(@root_dir)
287
+ @project_layer = filter_untrusted_project_config(@project_layer)
288
+ end
289
+
286
290
  @env_layer = EnvLoader.load_env(ENV, DEFAULT_CONFIG, @warnings)
287
291
  @session_layer = {}
288
292
 
@@ -29,9 +29,10 @@ module Rubik
29
29
  "Gemfile", "package.json", "Cargo.toml", "go.mod", "Makefile", "pyproject.toml", "Rakefile", "index.html", "README.md"
30
30
  ].freeze
31
31
 
32
- def initialize(root_dir: Dir.pwd, protocol_candidates: DEFAULT_PROTOCOL_CANDIDATES)
32
+ def initialize(root_dir: Dir.pwd, protocol_candidates: DEFAULT_PROTOCOL_CANDIDATES, config: nil)
33
33
  @root_dir = root_dir
34
34
  @protocol_candidates = protocol_candidates
35
+ @config = config
35
36
  end
36
37
 
37
38
  # Returns a Hash with three keys, each pre-extracted and pre-rendered
@@ -53,17 +54,35 @@ module Rubik
53
54
  end
54
55
 
55
56
  # Render the matched protocol files into an XML block.
57
+ # Caps content to avoid blowing out the context window (F3) and neutralizes
58
+ # closing tags to prevent prompt injection.
56
59
  def read_protocol_xml
57
60
  files = find_protocol_files
58
61
  return "" if files.empty?
59
62
 
60
- files.map do |f|
61
- content = Rubik::Platform.read_text(f[:full_path]).strip
62
- <<~XML
63
- <protocol source="#{f[:path]}">
64
- #{content}
65
- </protocol>
66
- XML
63
+ selection = (@config&.fetch("context.protocol_selection", "first") || "first").to_s
64
+ effective_files = selection == "all" ? files : files.first(1)
65
+ max_tokens = (@config&.fetch("context.protocol_max_tokens", 8192) || 8192).to_i
66
+ max_chars = [max_tokens * 4, 4096].max
67
+
68
+ effective_files.map do |f|
69
+ raw_content = Rubik::Platform.read_text(f[:full_path]).strip
70
+ # Neutralize closing tags to prevent section breakout
71
+ content = raw_content.gsub("</protocol>", "&lt;/protocol&gt;")
72
+ if content.length > max_chars
73
+ trunc = Rubik::Tools::Truncator.truncate(content, max_chars: max_chars, strategy: :head_tail)
74
+ <<~XML
75
+ <protocol source="#{f[:path]}" truncated="true">
76
+ #{trunc[:text]}
77
+ </protocol>
78
+ XML
79
+ else
80
+ <<~XML
81
+ <protocol source="#{f[:path]}">
82
+ #{content}
83
+ </protocol>
84
+ XML
85
+ end
67
86
  end.join("\n").strip
68
87
  end
69
88
 
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rubik
4
+ # THE single home of the event bus's name vocabulary. Publishers and
5
+ # subscribers across layers (orchestrator, repl, storage, kernel) read
6
+ # these constants instead of redeclaring the names — a redeclaration is
7
+ # one rename away from a silently dead subscription. Zero requires, a
8
+ # dependency-free leaf like Coeffects/Uris: any layer can bind to the
9
+ # shared names without dragging another layer's logic in.
10
+ module Events
11
+ SUBAGENT_COMPLETED = :subagent_completed
12
+ SUBAGENT_MESSAGE_TO_PARENT = :subagent_message_to_parent
13
+ TURN_FINISHED = :turn_finished
14
+ GOAL_FINISHED = :goal_finished
15
+ GOAL_SUSPENDED = :goal_suspended
16
+ UNIT_STATE_CHANGED = :unit_state_changed
17
+ end
18
+ end
@@ -126,7 +126,7 @@ module Rubik
126
126
 
127
127
  dispatch_event(item)
128
128
  rescue StandardError => e
129
- @logger&.error("Dispatcher worker error: #{e.message}")
129
+ @logger&.error("Dispatcher worker error: #{e.class}: #{e.message}")
130
130
  end
131
131
  end
132
132
 
@@ -140,11 +140,11 @@ module Rubik
140
140
  listener.arity.zero? ? listener.call : listener.call(event.payload)
141
141
  rescue StandardError => e
142
142
  begin
143
- @dmesg&.log(:kernel, :err, "Subscriber error on #{event.name}: #{e.message}")
143
+ @dmesg&.log(:kernel, :err, "Subscriber error on #{event.name}: #{e.class}: #{e.message}")
144
144
  rescue StandardError
145
145
  nil
146
146
  end
147
- @logger&.error("EventBus subscriber error on event '#{event.name}': #{e.message}")
147
+ @logger&.error("EventBus subscriber error on event '#{event.name}': #{e.class}: #{e.message}")
148
148
  end
149
149
 
150
150
  def log_to_dmesg(event)
@@ -160,7 +160,7 @@ module Rubik
160
160
  end
161
161
  @dmesg.log(event.subsystem, event.level, "event:#{event.name}", facility_id: fac_id, **safe_data)
162
162
  rescue StandardError => e
163
- @logger&.error("Dispatcher dmesg logging error: #{e.message}")
163
+ @logger&.error("Dispatcher dmesg logging error: #{e.class}: #{e.message}")
164
164
  end
165
165
  end
166
166
  end
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "monitor"
4
+ require_relative "../events"
4
5
 
5
6
  module Rubik
6
7
  module Kernel
@@ -98,9 +99,9 @@ module Rubik
98
99
  level = TRANSITION_SEVERITIES.fetch(to_state, :info)
99
100
  subsystem = (@type == :subagent ? :subagent : :kernel)
100
101
  @dmesg&.log(subsystem, level, msg, facility_id: @facility_id, unit_id: @id, from_state: from_state, to_state: to_state)
101
- @dispatcher&.post(:unit_state_changed, unit_id: @id, type: @type, from_state: from_state,
102
- to_state: to_state, reason: reason, facility_id: @facility_id,
103
- subsystem: subsystem, level: level)
102
+ @dispatcher&.post(Rubik::Events::UNIT_STATE_CHANGED, unit_id: @id, type: @type, from_state: from_state,
103
+ to_state: to_state, reason: reason, facility_id: @facility_id,
104
+ subsystem: subsystem, level: level)
104
105
  end
105
106
  end
106
107
 
data/lib/rubik/log.rb CHANGED
@@ -2,7 +2,8 @@
2
2
 
3
3
  # Central leveled logging core (G6 early slice): one seam for runtime
4
4
  # diagnostics, replacing ad-hoc Kernel#warn call sites as they are triaged
5
- # (see _plan/rescue-standarderror-triage-2026-09-29.md). Single-line format
5
+ # (bare-rescue/warn migration tracked in _plan/59-cekirdek-guvenligi-sentez-
6
+ # sandbox-bare-rescue-ve-moduler-testler.md and future audits). Single-line format
6
7
  # follows the repo's [rubik] prefix convention. Emit is error-isolated: a
7
8
  # logger must never raise, least of all from inside a rescue body.
8
9
  #