rubik 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. checksums.yaml +4 -4
  2. data/ATTRIBUTION.md +2 -2
  3. data/CHANGELOG.md +164 -1
  4. data/bin/rubik +15 -10
  5. data/lib/rubik/cli/workspace_trust.rb +1 -0
  6. data/lib/rubik/concurrency/worker.rb +143 -0
  7. data/lib/rubik/concurrency.rb +1 -0
  8. data/lib/rubik/config/deep_ops.rb +17 -0
  9. data/lib/rubik/config/defaults.rb +0 -1
  10. data/lib/rubik/config/schema.rb +0 -1
  11. data/lib/rubik/config.rb +7 -3
  12. data/lib/rubik/context/repo_context_reader.rb +27 -8
  13. data/lib/rubik/events.rb +18 -0
  14. data/lib/rubik/kernel/dispatcher.rb +19 -23
  15. data/lib/rubik/kernel/init.rb +22 -18
  16. data/lib/rubik/kernel/unit.rb +4 -3
  17. data/lib/rubik/orchestrator/auto_apply.rb +2 -0
  18. data/lib/rubik/orchestrator/budget_manager.rb +18 -2
  19. data/lib/rubik/orchestrator/goal_ledger/deep_ops.rb +41 -0
  20. data/lib/rubik/orchestrator/goal_ledger/drift.rb +2 -1
  21. data/lib/rubik/orchestrator/goal_ledger/ledger.rb +59 -59
  22. data/lib/rubik/orchestrator/goal_ledger/observation_projection.rb +29 -9
  23. data/lib/rubik/orchestrator/goal_ledger/patch.rb +10 -17
  24. data/lib/rubik/orchestrator/goal_ledger/suspend_lifecycle.rb +9 -41
  25. data/lib/rubik/orchestrator/goal_ledger/validator.rb +6 -20
  26. data/lib/rubik/orchestrator/goal_ledger/verifier.rb +3 -14
  27. data/lib/rubik/orchestrator/goal_ledger/xml_render.rb +21 -14
  28. data/lib/rubik/orchestrator/goal_state.rb +15 -15
  29. data/lib/rubik/orchestrator/loop.rb +62 -63
  30. data/lib/rubik/orchestrator/lsp_feedback.rb +7 -1
  31. data/lib/rubik/orchestrator/subagent/admission_policy.rb +161 -0
  32. data/lib/rubik/orchestrator/subagent/builtin_types.rb +3 -2
  33. data/lib/rubik/orchestrator/subagent/deferred_spec.rb +51 -2
  34. data/lib/rubik/orchestrator/subagent/dependency.rb +20 -20
  35. data/lib/rubik/orchestrator/subagent/execution_reads.rb +1 -1
  36. data/lib/rubik/orchestrator/subagent/journal.rb +3 -9
  37. data/lib/rubik/orchestrator/subagent/lifecycle.rb +10 -1
  38. data/lib/rubik/orchestrator/subagent/notices.rb +5 -4
  39. data/lib/rubik/orchestrator/subagent/paging.rb +49 -0
  40. data/lib/rubik/orchestrator/subagent/profile_contract.rb +4 -10
  41. data/lib/rubik/orchestrator/subagent/reaper.rb +1 -3
  42. data/lib/rubik/orchestrator/subagent/redeploy_transaction.rb +99 -0
  43. data/lib/rubik/orchestrator/subagent/result_archive.rb +12 -22
  44. data/lib/rubik/orchestrator/subagent/reuse.rb +37 -31
  45. data/lib/rubik/orchestrator/subagent/run_cycle.rb +22 -1
  46. data/lib/rubik/orchestrator/subagent/scoped_registry.rb +34 -2
  47. data/lib/rubik/orchestrator/subagent/spawn_transaction.rb +1 -1
  48. data/lib/rubik/orchestrator/subagent/supervisor.rb +6 -2
  49. data/lib/rubik/orchestrator/subagent/task_ownership.rb +2 -2
  50. data/lib/rubik/orchestrator/subagent/transcript_reader.rb +14 -13
  51. data/lib/rubik/orchestrator/subagent/type_registry.rb +19 -1
  52. data/lib/rubik/orchestrator/turn_executor/subagent_channel.rb +6 -1
  53. data/lib/rubik/orchestrator/turn_executor/user_channel.rb +6 -1
  54. data/lib/rubik/orchestrator/turn_executor.rb +2 -1
  55. data/lib/rubik/platform/path.rb +0 -1
  56. data/lib/rubik/prompt/context_builder.rb +24 -18
  57. data/lib/rubik/prompt/context_compactor.rb +31 -8
  58. data/lib/rubik/prompt/conversation_rows.rb +33 -0
  59. data/lib/rubik/prompt/doctrine.rb +4 -2
  60. data/lib/rubik/prompt/emergency_compactor.rb +5 -4
  61. data/lib/rubik/repl/commands/agent_execution.rb +13 -2
  62. data/lib/rubik/repl/commands/buffer.rb +4 -0
  63. data/lib/rubik/repl/commands/mcp.rb +5 -0
  64. data/lib/rubik/repl/commands/subagents.rb +7 -6
  65. data/lib/rubik/repl/commands/workspace.rb +22 -2
  66. data/lib/rubik/repl/config_wiring.rb +24 -7
  67. data/lib/rubik/repl/input_execution.rb +1 -1
  68. data/lib/rubik/repl/lifecycle.rb +3 -2
  69. data/lib/rubik/repl/pruner/harness.rb +52 -67
  70. data/lib/rubik/repl/pruner/rules.rb +3 -1
  71. data/lib/rubik/repl/pruner/service.rb +4 -9
  72. data/lib/rubik/repl/service_catalog.rb +1 -1
  73. data/lib/rubik/repl/synthesized_command_context.rb +3 -0
  74. data/lib/rubik/repl/turn_recorder.rb +5 -4
  75. data/lib/rubik/repl.rb +1 -0
  76. data/lib/rubik/runtime/context.rb +11 -1
  77. data/lib/rubik/runtime/discovery.rb +55 -0
  78. data/lib/rubik/runtime/fiber.rb +17 -5
  79. data/lib/rubik/runtime/manager.rb +19 -12
  80. data/lib/rubik/runtime/overlay_storage.rb +54 -23
  81. data/lib/rubik/runtime/repair_probe.rb +20 -2
  82. data/lib/rubik/runtime/sealed_coeffects.rb +58 -0
  83. data/lib/rubik/runtime/synthesized_command_context.rb +80 -0
  84. data/lib/rubik/runtime/synthesized_tool_context.rb +123 -0
  85. data/lib/rubik/runtime.rb +2 -0
  86. data/lib/rubik/security/classifier/classifier.rb +16 -8
  87. data/lib/rubik/security/classifier/commands/biome.yaml +49 -0
  88. data/lib/rubik/security/classifier/commands/bun.yaml +91 -0
  89. data/lib/rubik/security/classifier/commands/bundle.yaml +107 -0
  90. data/lib/rubik/security/classifier/commands/clang-format.yaml +21 -0
  91. data/lib/rubik/security/classifier/commands/clang.yaml +37 -0
  92. data/lib/rubik/security/classifier/commands/cmake.yaml +37 -0
  93. data/lib/rubik/security/classifier/commands/ctest.yaml +30 -0
  94. data/lib/rubik/security/classifier/commands/gcc.yaml +36 -0
  95. data/lib/rubik/security/classifier/commands/gem.yaml +104 -0
  96. data/lib/rubik/security/classifier/commands/gofmt.yaml +15 -0
  97. data/lib/rubik/security/classifier/commands/pnpm.yaml +8 -8
  98. data/lib/rubik/security/classifier/commands/python.yaml +18 -1
  99. data/lib/rubik/security/classifier/commands/python3.yaml +18 -1
  100. data/lib/rubik/security/classifier/commands/rake.yaml +60 -0
  101. data/lib/rubik/security/classifier/commands/rspec.yaml +42 -0
  102. data/lib/rubik/security/classifier/commands/rubocop.yaml +38 -0
  103. data/lib/rubik/security/classifier/commands/ruby.yaml +25 -0
  104. data/lib/rubik/security/classifier/commands/rustc.yaml +34 -0
  105. data/lib/rubik/security/classifier/commands/zig.yaml +77 -0
  106. data/lib/rubik/security/classifier/database.rb +12 -1
  107. data/lib/rubik/security/classifier/matcher.rb +17 -2
  108. data/lib/rubik/security/classifier/models.rb +3 -2
  109. data/lib/rubik/security/classifier.rb +5 -0
  110. data/lib/rubik/security/guard.rb +133 -39
  111. data/lib/rubik/storage/layout.rb +14 -3
  112. data/lib/rubik/storage/vakanuvis/harness.rb +49 -89
  113. data/lib/rubik/tools/base.rb +55 -7
  114. data/lib/rubik/tools/builtins/dmesg.rb +1 -1
  115. data/lib/rubik/tools/builtins/exec.rb +1 -2
  116. data/lib/rubik/tools/builtins/files.rb +3 -1
  117. data/lib/rubik/tools/builtins/goal_ledger.rb +10 -10
  118. data/lib/rubik/tools/builtins/grep.rb +2 -2
  119. data/lib/rubik/tools/builtins/interactive.rb +1 -3
  120. data/lib/rubik/tools/builtins/lifecycle.rb +1 -1
  121. data/lib/rubik/tools/builtins/lsp.rb +2 -2
  122. data/lib/rubik/tools/builtins/pruner.rb +1 -1
  123. data/lib/rubik/tools/builtins/runtime.rb +1 -1
  124. data/lib/rubik/tools/builtins/send_message.rb +14 -3
  125. data/lib/rubik/tools/builtins/skill.rb +1 -1
  126. data/lib/rubik/tools/builtins/storage.rb +1 -1
  127. data/lib/rubik/tools/builtins/subagent.rb +2 -1
  128. data/lib/rubik/tools/builtins/subagent_lifecycle.rb +5 -3
  129. data/lib/rubik/tools/builtins/symbols.rb +4 -4
  130. data/lib/rubik/tools/builtins/synthesis.rb +121 -64
  131. data/lib/rubik/tools/builtins/task.rb +1 -1
  132. data/lib/rubik/tools/builtins/unsynthesize.rb +38 -0
  133. data/lib/rubik/tools/builtins/vakanuvis.rb +1 -1
  134. data/lib/rubik/tools/catalog.rb +3 -0
  135. data/lib/rubik/tools/declaration.rb +6 -2
  136. data/lib/rubik/tools/preflight_runner.rb +107 -14
  137. data/lib/rubik/tools/registry.rb +2 -0
  138. data/lib/rubik/tools/uri_resolver.rb +3 -1
  139. data/lib/rubik/uris.rb +5 -1
  140. data/lib/rubik/version.rb +1 -1
  141. data/lib/rubik.rb +1 -0
  142. metadata +27 -1
@@ -66,6 +66,10 @@ module Rubik
66
66
 
67
67
  @type_registry = TypeRegistry.new(default_context: @root_context)
68
68
  @instances = {}
69
+ # Tombstone table (reaped executions) is born here beside its
70
+ # sibling maps — ReaperSupervisor writes it, every reader may
71
+ # assume it is initialized.
72
+ @finished = {}
69
73
  @deferred = {}
70
74
  @monitor = Monitor.new
71
75
  @wait_cond = @monitor.new_cond
@@ -95,7 +99,7 @@ module Rubik
95
99
  @root_context.register_disposable { shutdown_all } if @root_context.respond_to?(:register_disposable)
96
100
  end
97
101
 
98
- def get(id) = @monitor.synchronize { @instances[id.to_s] || (@finished ||= {})[id.to_s] || queued_spec(id.to_s) }
102
+ def get(id) = @monitor.synchronize { @instances[id.to_s] || @finished[id.to_s] || queued_spec(id.to_s) }
99
103
 
100
104
  def extend_budget(id, steps = Budget::DEFAULT_GRANT_STEPS)
101
105
  inst = get(id)
@@ -125,7 +129,7 @@ module Rubik
125
129
 
126
130
  def list(parent_id: nil)
127
131
  @monitor.synchronize do
128
- items = @instances.values + (@finished ||= {}).values + @deferred.values
132
+ items = @instances.values + @finished.values + @deferred.values
129
133
  items = items.select { |i| i.parent_id == parent_id.to_s } if parent_id
130
134
  items.sort_by { |i| i.started_at || Time.at(0) }
131
135
  end
@@ -51,7 +51,7 @@ module Rubik
51
51
  end
52
52
 
53
53
  remaining = @monitor.synchronize do
54
- (@instances.values + (@finished || {}).values + requested.values).uniq.select do |inst|
54
+ (@instances.values + @finished.values + requested.values).uniq.select do |inst|
55
55
  owned_by?(inst, token) && !cancellation_settled?(inst)
56
56
  end
57
57
  end
@@ -97,7 +97,7 @@ module Rubik
97
97
  def cancel_queued_specs(token)
98
98
  queued = @monitor.synchronize do
99
99
  specs = @deferred.values.select { |spec| spec.respond_to?(:owner) && spec.owner.equal?(token) }
100
- specs.each { |spec| cancel_spec!(spec, "owner task cancelled (^C)") }
100
+ specs.each { |spec| spec.cancel!("owner task cancelled (^C)") }
101
101
  specs
102
102
  end
103
103
  announce_cancellations(queued)
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "digest"
4
+ require_relative "paging"
4
5
  require_relative "transcript_formatter"
5
6
  require_relative "../../uris"
6
7
 
@@ -21,8 +22,12 @@ module Rubik
21
22
  # execution state, and never touch the workspace gate: live comes from
22
23
  # the instance roster, disk from the execution's own storage-id path.
23
24
  module TranscriptReader
24
- # A live execution whose memory snapshot is the freshest source.
25
- ACTIVE_STATES = ["pending", "running", "waiting_input", "waiting_budget", "paused_error", "canceling", "queued"].freeze
25
+ # A live execution whose memory snapshot is the freshest source. The
26
+ # instance vocabulary only — "queued" was dead data here: an Instance
27
+ # can never hold :queued (TRANSITIONS has no such state), and the
28
+ # tool plane resolves queued specs to their own handling before
29
+ # read_transcript is ever reached.
30
+ ACTIVE_STATES = ["pending", "running", "waiting_input", "waiting_budget", "paused_error", "canceling"].freeze
26
31
 
27
32
  # Page size stays under the tool-output truncation ceiling (head_tail
28
33
  # would otherwise eat the middle of a page); the hard cap bounds a
@@ -135,20 +140,16 @@ module Rubik
135
140
  "Start a new read at cursor 0 to get a consistent snapshot.")
136
141
  end
137
142
 
138
- total = text.length
139
- cur = [cursor.to_i, 0].max
140
- return missing(sid, :cursor, "Cursor #{cur} exceeds the transcript length (#{total} chars). Use cursor 0.") if cur > total
143
+ win = Paging.window(text, cursor: cursor, limit: limit, default: DEFAULT_PAGE_CHARS, max: MAX_PAGE_CHARS)
144
+ unless win
145
+ cur = Paging.clamp_cursor(cursor)
146
+ return missing(sid, :cursor, "Cursor #{cur} exceeds the transcript length (#{text.length} chars). Use cursor 0.")
147
+ end
141
148
 
142
- size = limit.to_i
143
- size = DEFAULT_PAGE_CHARS if size <= 0
144
- size = [size, MAX_PAGE_CHARS].min
145
- body = text[cur, size].to_s
146
- nxt = cur + body.length
147
- has_more = nxt < total
148
149
  Page.new(storage_id: sid, id: instance&.id, source: source, snapshot: token,
149
150
  state: instance.respond_to?(:state) ? instance.state&.to_s : nil, persisted: source == "disk",
150
- body: body, cursor: cur, next_cursor: has_more ? nxt : nil, total_chars: total,
151
- returned_chars: body.length, has_more: has_more)
151
+ body: win.body, cursor: win.cursor, next_cursor: win.next_cursor, total_chars: win.total_chars,
152
+ returned_chars: win.returned_chars, has_more: win.has_more)
152
153
  end
153
154
 
154
155
  def missing(storage_id, reason, message)
@@ -34,6 +34,7 @@ module Rubik
34
34
  private :register_builtin
35
35
 
36
36
  def register(type_def, context: nil, replace: false)
37
+ reject_caller_tool_filter(type_def)
37
38
  profile = validate_registered_profile(type_def)
38
39
  apply_profile_contract(type_def, profile)
39
40
  register_dynamic(type_def, context: context || type_def.context || @default_context, replace: replace)
@@ -168,10 +169,27 @@ module Rubik
168
169
  type_def.system_prompt = profile.system_prompt
169
170
  type_def.requires = profile.requires
170
171
  type_def.grants = profile.grants
171
- type_def.tool_filter = ProfileContract.tool_filter(profile.grants)
172
+ type_def.tool_filter = ProfileContract.tool_filter(profile.grants).tap do |filter|
173
+ # Mark the installed filter so re-registering the same def (the
174
+ # registry mutated it) is not mistaken for a caller-provided one.
175
+ type_def.instance_variable_set(:@contract_filter, filter)
176
+ end
172
177
  type_def.enable_write_tools = profile.grants.include?("write")
173
178
  type_def.enable_subagent_tools = profile.grants.include?("subagent_spawn")
174
179
  end
180
+
181
+ # The registry installs the profile-contract filter and never honors
182
+ # a caller-provided one — accepting it (validating its shape, then
183
+ # silently discarding it) would hide a discarded security decision,
184
+ # so it is rejected up front.
185
+ def reject_caller_tool_filter(type_def)
186
+ return unless type_def.tool_filter
187
+ return if type_def.tool_filter.equal?(type_def.instance_variable_get(:@contract_filter))
188
+
189
+ raise ArgumentError,
190
+ "type '#{type_def.name}' declares tool_filter; the registry installs the profile-contract filter " \
191
+ "(ProfileContract.tool_filter(grants)) and never honors a caller filter — express intent via grants."
192
+ end
175
193
  end
176
194
  end
177
195
  end
@@ -23,7 +23,12 @@ module Rubik
23
23
  def tool_registry = @inst.tool_registry
24
24
 
25
25
  def limits
26
- { context_limit: @inst.context_limit, max_output_tokens: @inst.max_output_tokens, config: @inst.config }
26
+ reserved = if @inst.respond_to?(:tool_registry) && @inst.tool_registry&.schemas
27
+ Rubik::Prompt::TokenEstimator.estimate_tool_schemas(@inst.tool_registry.schemas)
28
+ else
29
+ 0
30
+ end
31
+ { context_limit: @inst.context_limit, max_output_tokens: @inst.max_output_tokens, config: @inst.config, reserved_tokens: reserved }
27
32
  end
28
33
 
29
34
  # Subagent policy (ToolCallId doctrine): deterministic
@@ -36,7 +36,12 @@ module Rubik
36
36
  end
37
37
 
38
38
  def limits
39
- { context_limit: @deps.context_limit, max_output_tokens: @deps.max_output_tokens, config: @deps.config }
39
+ reserved = if @deps.respond_to?(:tool_registry) && @deps.tool_registry&.schemas
40
+ Rubik::Prompt::TokenEstimator.estimate_tool_schemas(@deps.tool_registry.schemas)
41
+ else
42
+ 0
43
+ end
44
+ { context_limit: @deps.context_limit, max_output_tokens: @deps.max_output_tokens, config: @deps.config, reserved_tokens: reserved }
40
45
  end
41
46
 
42
47
  # Loop policy (ToolCallId doctrine): unique-by-suffix ids — the
@@ -122,7 +122,8 @@ module Rubik
122
122
  layer = Rubik::Prompt::EmergencyCompactor.compact!(
123
123
  channel.history, context_limit: limits[:context_limit], max_output_tokens: limits[:max_output_tokens],
124
124
  config: ProviderRecovery.compaction_config(limits[:config]),
125
- absorb: channel.absorb_directive
125
+ absorb: channel.absorb_directive,
126
+ reserved_tokens: limits[:reserved_tokens] || 0
126
127
  )
127
128
  channel.announce_compaction(reason, layer)
128
129
  layer
@@ -214,7 +214,6 @@ module Rubik
214
214
  roots << ENV["CommonProgramFiles"] if ENV["CommonProgramFiles"]
215
215
  roots << ENV["USERPROFILE"] if ENV["USERPROFILE"]
216
216
  roots << "#{ENV['SystemDrive']}/" if ENV["SystemDrive"]
217
- roots << ENV["SystemDrive"] if ENV["SystemDrive"]
218
217
  end
219
218
  roots << home_dir
220
219
  roots.compact.map { |r| normalize_path(r) }.uniq
@@ -20,8 +20,8 @@ module Rubik
20
20
  Rubik::Context::RepoContextReader.new(root_dir: root_dir).find_protocol_files
21
21
  end
22
22
 
23
- def self.build_protocol_xml(root_dir = Dir.pwd)
24
- Rubik::Context::RepoContextReader.new(root_dir: root_dir).read_protocol_xml
23
+ def self.build_protocol_xml(root_dir = Dir.pwd, config: nil)
24
+ Rubik::Context::RepoContextReader.new(root_dir: root_dir, config: config).read_protocol_xml
25
25
  end
26
26
 
27
27
  def self.build_workspace_xml(context_index = nil, root_dir = Dir.pwd)
@@ -165,9 +165,10 @@ module Rubik
165
165
  custom = commands.select { |_k, v| v.is_a?(Hash) && v[:custom] }
166
166
  return "" if custom.empty?
167
167
 
168
+ esc = Rubik::Platform.method(:xml_escape)
168
169
  cmd_tags = custom.sort.map do |name, meta|
169
170
  desc = (meta.is_a?(Hash) ? meta[:description] : meta) || ""
170
- " <command name=\"!#{name}\">#{desc}</command>"
171
+ " <command name=\"!#{esc.call(name.to_s)}\">#{esc.call(desc.to_s)}</command>"
171
172
  end.join("\n")
172
173
  "<custom_commands>\n#{cmd_tags}\n</custom_commands>"
173
174
  end
@@ -198,13 +199,7 @@ module Rubik
198
199
  esc = Rubik::Platform.method(:xml_escape)
199
200
  tags = types.map do |t|
200
201
  name = esc.call(t.name.to_s)
201
- tools_mode = if t.name.to_s == "self"
202
- "full_clone"
203
- elsif t.enable_write_tools
204
- "read_write_test"
205
- else
206
- "read_only"
207
- end
202
+ tools_mode = Rubik::Orchestrator::Subagent::AdmissionPolicy.capability_label(t)
208
203
  workspace = t.name.to_s == "coder" ? "branch" : "inherit"
209
204
  desc = esc.call(t.description.to_s)
210
205
  " <subagent name=\"#{name}\" tools=\"#{tools_mode}\" default_workspace=\"#{workspace}\">#{desc}</subagent>"
@@ -243,7 +238,7 @@ module Rubik
243
238
  end
244
239
  private_class_method :prompt_visible_subagent_types
245
240
 
246
- def self.build_lsp_xml(lsp_manager = nil)
241
+ def self.build_lsp_xml(lsp_manager = nil, max_diagnostics: 50)
247
242
  return "" unless lsp_manager&.enabled?
248
243
 
249
244
  summary = lsp_manager.status_summary
@@ -251,7 +246,7 @@ module Rubik
251
246
 
252
247
  all_diags = lsp_manager.all_diagnostics
253
248
  total_errors = 0
254
- diag_tags = []
249
+ parsed_diags = []
255
250
 
256
251
  all_diags.each do |fpath, diags|
257
252
  diags.each do |d|
@@ -259,7 +254,10 @@ module Rubik
259
254
  total_errors += 1 if sev == "error"
260
255
  start_line = (d.dig("range", "start", "line") || 0) + 1
261
256
  msg = Rubik::Platform.xml_escape(d["message"])
262
- diag_tags << " <diagnostic file=\"#{Rubik::Platform.xml_escape(fpath)}\" line=\"#{start_line}\" severity=\"#{sev}\">#{msg}</diagnostic>"
257
+ parsed_diags << {
258
+ severity: sev,
259
+ tag: " <diagnostic file=\"#{Rubik::Platform.xml_escape(fpath)}\" line=\"#{start_line}\" severity=\"#{sev}\">#{msg}</diagnostic>"
260
+ }
263
261
  end
264
262
  end
265
263
 
@@ -274,14 +272,21 @@ module Rubik
274
272
  lsp_diagnostics/lsp_hover will return nothing — use run_command or
275
273
  read tools instead.
276
274
  XML
277
- elsif diag_tags.empty?
275
+ elsif parsed_diags.empty?
278
276
  <<~XML.strip
279
277
  <lsp_status enabled="true" active_servers="#{Rubik::Platform.xml_escape(active_servers.join(', '))}" clean="true" />
280
278
  XML
281
279
  else
280
+ # Prioritize errors before warnings when capping
281
+ sorted_diags = parsed_diags.sort_by { |d| d[:severity] == "error" ? 0 : 1 }
282
+ shown_diags = sorted_diags.first(max_diagnostics).map { |d| d[:tag] }
283
+ omitted_count = parsed_diags.size - shown_diags.size
284
+ omitted_notice = omitted_count.positive? ? "\n <!-- #{omitted_count} additional diagnostics omitted for brevity -->" : ""
285
+ shown_attr = omitted_count.positive? ? " shown=\"#{shown_diags.size}\"" : ""
286
+
282
287
  <<~XML.strip
283
- <lsp_diagnostics active_servers="#{Rubik::Platform.xml_escape(active_servers.join(', '))}" total_issues="#{diag_tags.size}" errors="#{total_errors}">
284
- #{diag_tags.join("\n")}
288
+ <lsp_diagnostics active_servers="#{Rubik::Platform.xml_escape(active_servers.join(', '))}" total_issues="#{parsed_diags.size}" errors="#{total_errors}"#{shown_attr}>
289
+ #{shown_diags.join("\n")}#{omitted_notice}
285
290
  </lsp_diagnostics>
286
291
  XML
287
292
  end
@@ -303,7 +308,7 @@ module Rubik
303
308
  # ShellResolver the sandbox driver spawns through.
304
309
  sections << Rubik::Sandbox::ShellResolver.environment_line(svc.config&.fetch("sandbox.shell", "auto") || "auto")
305
310
 
306
- protocol_xml = build_protocol_xml(svc.root_dir)
311
+ protocol_xml = build_protocol_xml(svc.root_dir, config: svc.config)
307
312
  sections << protocol_xml unless protocol_xml.empty?
308
313
 
309
314
  workspace_xml = build_workspace_xml(svc.context_index, svc.root_dir)
@@ -403,7 +408,8 @@ module Rubik
403
408
 
404
409
  def self.detect_git_branch(root_dir)
405
410
  Rubik::Context::RepoContextReader.new(root_dir: root_dir).read_git_branch
406
- rescue StandardError
411
+ rescue StandardError => e
412
+ Rubik::Log.warn(:context, "detect_git_branch failed: #{e.class}: #{e.message}")
407
413
  nil
408
414
  end
409
415
  end
@@ -13,21 +13,23 @@ module Rubik
13
13
 
14
14
  module_function
15
15
 
16
- def effective_input_ceiling(context_limit:, max_output_tokens: 4096, safety_margin: 1024)
17
- [1024, context_limit.to_i - max_output_tokens.to_i - safety_margin.to_i].max
16
+ def effective_input_ceiling(context_limit:, max_output_tokens: 4096, safety_margin: 1024, reserved_tokens: 0)
17
+ [1024, context_limit.to_i - max_output_tokens.to_i - safety_margin.to_i - reserved_tokens.to_i].max
18
18
  end
19
19
 
20
- def needs_compaction?(history, context_limit:, max_output_tokens: 4096, safety_margin: 1024, max_tokens_ratio: 0.85, config: {})
20
+ def needs_compaction?(history, context_limit:, max_output_tokens: 4096, safety_margin: 1024, max_tokens_ratio: 0.85, config: {}, reserved_tokens: 0)
21
21
  return false if history.nil? || history.empty?
22
22
 
23
23
  ratio = (config["max_tokens_ratio"] || config[:max_tokens_ratio] || max_tokens_ratio || 0.85).to_f
24
24
  margin = (config["safety_margin_tokens"] || config[:safety_margin_tokens] || safety_margin || 1024).to_i
25
25
  max_out = (config["max_output_tokens"] || config[:max_output_tokens] || max_output_tokens || 4096).to_i
26
+ reserved = (config["reserved_tokens"] || config[:reserved_tokens] || reserved_tokens || 0).to_i
26
27
 
27
28
  ceiling = effective_input_ceiling(
28
29
  context_limit: context_limit,
29
30
  max_output_tokens: max_out,
30
- safety_margin: margin
31
+ safety_margin: margin,
32
+ reserved_tokens: reserved
31
33
  )
32
34
  threshold = (ceiling * ratio).to_i
33
35
  total_tokens = TokenEstimator.estimate_history(history)
@@ -38,7 +40,7 @@ module Rubik
38
40
  # iken tier atlanır ve davranış bit-bit aynıdır; verilirse dup
39
41
  # kopyaya #apply!(rows) uygulanır (prompt katmanı goal bilmez;
40
42
  # directive'i orchestrator/goal_ledger ailesi kurar).
41
- def compact_history(history, context_limit:, max_output_tokens: 4096, safety_margin: 1024, config: {}, force: false, absorb: nil)
43
+ def compact_history(history, context_limit:, max_output_tokens: 4096, safety_margin: 1024, config: {}, force: false, absorb: nil, reserved_tokens: 0)
42
44
  return [] if history.nil? || history.empty?
43
45
 
44
46
  strategy = (config["compaction_strategy"] || config[:compaction_strategy] || "hybrid").to_s
@@ -49,11 +51,14 @@ module Rubik
49
51
  preserve_first_n = (config["preserve_first_n"] || config[:preserve_first_n] || 2).to_i
50
52
  preserve_last_n = (config["preserve_last_n"] || config[:preserve_last_n] || 6).to_i
51
53
  safety_margin = (config["safety_margin_tokens"] || config[:safety_margin_tokens] || safety_margin || 1024).to_i
54
+ max_out = (config["max_output_tokens"] || config[:max_output_tokens] || max_output_tokens || 4096).to_i
55
+ reserved = (config["reserved_tokens"] || config[:reserved_tokens] || reserved_tokens || 0).to_i
52
56
 
53
57
  ceiling = effective_input_ceiling(
54
58
  context_limit: context_limit,
55
- max_output_tokens: max_output_tokens,
56
- safety_margin: safety_margin
59
+ max_output_tokens: max_out,
60
+ safety_margin: safety_margin,
61
+ reserved_tokens: reserved
57
62
  )
58
63
  threshold = (ceiling * max_tokens_ratio).to_i
59
64
 
@@ -173,6 +178,14 @@ module Rubik
173
178
  role == "user" && content.include?("<user_task>") && content.include?("</user_task>")
174
179
  end
175
180
 
181
+ # Σ satırı gramerinin tek evi: etiket adları hem render (XmlRender,
182
+ # DriftNote) hem tanıma (ledger_message?/drift_message?) hem de pruner
183
+ # enjeksiyon-kaçışı yüzeylerince tüketilir — önek yalnız burada doğar,
184
+ # herkes aynı sabitten okur. Ayrı sabitler: `<goal_ledger ` ve
185
+ # `<ledger_drift ` satırları farklı pin/pin-dışı kontratlara sahiptir.
186
+ GOAL_LEDGER_TAG = "goal_ledger"
187
+ LEDGER_DRIFT_TAG = "ledger_drift"
188
+
176
189
  # Yapılandırılmış goal ledger satırı mı? (goal-ledger planı A) —
177
190
  # goal_message? ile aynı alıntı-tek-etiket disiplini: açılış
178
191
  # `<goal_ledger ` + kapanış `</goal_ledger>` BİRLİKTE aranır; kullanıcı
@@ -183,7 +196,17 @@ module Rubik
183
196
 
184
197
  role = ConversationRows.role_of(msg)
185
198
  content = ConversationRows.content_of(msg).to_s
186
- role == "user" && content.start_with?("<goal_ledger ") && content.include?("</goal_ledger>")
199
+ role == "user" && content.start_with?("<#{GOAL_LEDGER_TAG} ") && content.include?("</#{GOAL_LEDGER_TAG}>")
200
+ end
201
+
202
+ # Drift yeniden-enjeksiyon taşıyıcısı (DriftNote) — ledger_message?
203
+ # ile aynı alıntı-tek-etiket disiplini; etiket adı LEDGER_DRIFT_TAG.
204
+ def drift_message?(msg)
205
+ return false unless ConversationRows.row?(msg)
206
+
207
+ role = ConversationRows.role_of(msg)
208
+ content = ConversationRows.content_of(msg).to_s
209
+ role == "user" && content.start_with?("<#{LEDGER_DRIFT_TAG} ") && content.include?("</#{LEDGER_DRIFT_TAG}>")
187
210
  end
188
211
 
189
212
  # İsim korunur (pruner rules.rb:39 çağrısı yük taşıyor): pin ailesi
@@ -43,6 +43,39 @@ module Rubik
43
43
  # match), preserving current behavior bit-for-bit.
44
44
  def user_row?(row) = row[:role] == "user" || row["role"] == "user"
45
45
 
46
+ # Dialogue turn sanitizer for prior history and session restoration.
47
+ # Defends against unauthorized role injection (e.g. injected "system" role)
48
+ # and unescaped structural pin tags (<user_task>, <protocol>).
49
+ def sanitize_dialogue_turn(turn)
50
+ return nil unless row?(turn)
51
+
52
+ role = role_of(turn).strip.downcase
53
+ return nil unless ["user", "assistant", "tool"].include?(role)
54
+
55
+ raw_content = content_of(turn)
56
+ tool_calls = value_of(turn, :tool_calls)
57
+ tool_call_id = value_of(turn, :tool_call_id)
58
+ tool_name = value_of(turn, :tool_name)
59
+
60
+ empty_content = raw_content.nil? || raw_content.to_s.strip.empty?
61
+ no_tools = (tool_calls.nil? || tool_calls.empty?) && tool_call_id.nil?
62
+ return nil if empty_content && no_tools
63
+
64
+ content = raw_content.to_s
65
+ if role == "user"
66
+ content = content.gsub("<user_task>", "&lt;user_task&gt;")
67
+ .gsub("</user_task>", "&lt;/user_task&gt;")
68
+ .gsub("<protocol>", "&lt;protocol&gt;")
69
+ .gsub("</protocol>", "&lt;/protocol&gt;")
70
+ end
71
+
72
+ sanitized = { role: role, content: content }
73
+ sanitized[:tool_calls] = tool_calls if tool_calls && !tool_calls.empty?
74
+ sanitized[:tool_call_id] = tool_call_id.to_s if tool_call_id
75
+ sanitized[:tool_name] = tool_name.to_s if tool_name
76
+ sanitized
77
+ end
78
+
46
79
  # The notice-merge policy, previously duplicated in
47
80
  # Orchestrator::Loop#merge_notice_block_into_history! and
48
81
  # Lifecycle#inject_subagent_notice_into_conversation_history!.
@@ -62,9 +62,11 @@ module Rubik
62
62
  HDR
63
63
  when :goal
64
64
  ledger_active = goal_ledger && tool_active?("update_goal_ledger", active_tools)
65
- ledger_line = " If a `<goal_ledger>` row is present, keep its state current: read `rubik://goal/ledger` and " \
65
+ ledger_line = " If a `<goal_ledger>` row is present, keep its state current: read `rubik://goal/ledger` (or `.json`) and " \
66
66
  "apply JSON patches with `update_goal_ledger(patch: ...)` against the reported rev after each " \
67
- "meaningful step (task status changes, new findings/decisions)."
67
+ "meaningful step (task status changes, new findings/decisions). Tasks and environment notes can carry " \
68
+ "declarative `verify` specifications ({\"type\": \"file_exists\"|\"file_contains\"|\"marker\", \"path\": ...}) " \
69
+ "that the harness autonomously re-verifies against the filesystem at step boundaries."
68
70
  <<~HDR
69
71
  You are Rubik (maestro), an autonomous AI coding SUPERVISOR in AUTONOMOUS GOAL mode.
70
72
  You own the goal in <user_task> and MUST drive it to verified completion as a pure orchestrator — you conduct, subagents perform. You may perform lightweight read-only inspection (`list_files`, `grep_search`, `read_file`) to orient and shape assignments, while all broader research, code changes, and verification run in subagent contexts, never in yours:
@@ -31,19 +31,20 @@ module Rubik
31
31
  # :hard_truncate); the nil/empty guards return the input unchanged
32
32
  # (pinned by tests). The return value is observational: callers forward
33
33
  # it on the :emergency_compact on_step event rather than branch on it.
34
- def compact!(history, context_limit: nil, max_output_tokens: nil, config: {}, absorb: nil)
34
+ def compact!(history, context_limit: nil, max_output_tokens: nil, config: {}, absorb: nil, reserved_tokens: 0)
35
35
  return history if history.nil? || history.empty?
36
36
 
37
37
  config = {} unless config.is_a?(Hash) # a null `context:` YAML section makes fetch return nil
38
- max_out = max_output_tokens || 4096
38
+ max_out = (config["max_output_tokens"] || config[:max_output_tokens] || max_output_tokens || 4096).to_i
39
+ reserved = (config["reserved_tokens"] || config[:reserved_tokens] || reserved_tokens || 0).to_i
39
40
  if context_limit&.positive?
40
41
  structural = Rubik::Prompt::ContextCompactor.compact_history(
41
42
  history, context_limit: context_limit,
42
- max_output_tokens: max_out, config: config, force: true, absorb: absorb
43
+ max_output_tokens: max_out, config: config, force: true, absorb: absorb, reserved_tokens: reserved
43
44
  )
44
45
  history.replace(structural)
45
46
  still_over = Rubik::Prompt::ContextCompactor.needs_compaction?(
46
- history, context_limit: context_limit, max_output_tokens: max_out, config: config
47
+ history, context_limit: context_limit, max_output_tokens: max_out, config: config, reserved_tokens: reserved
47
48
  )
48
49
  return :structural unless still_over
49
50
  end
@@ -231,7 +231,8 @@ module Rubik
231
231
  # eşlemesine düşülmesin.
232
232
  if e.respond_to?(:transient?) && e.transient?
233
233
  suspend_goal_turn(ctx, orchestrator: orchestrator, goal_state: goal_state, goal_ledger: goal_ledger,
234
- goal_text: goal_text, goal_id: goal_id, record_pair: record_pair, reason: e.message)
234
+ goal_text: goal_text, goal_id: goal_id, record_pair: record_pair, reason: e.message,
235
+ tokens: orchestrator.total_tokens)
235
236
  else
236
237
  fail_goal_turn(ctx, goal_state: goal_state, goal_ledger: goal_ledger, goal_id: goal_id,
237
238
  record_pair: record_pair, reason: e.message)
@@ -298,7 +299,9 @@ module Rubik
298
299
  # olayları loop inbox'a girer ve devam adımında boşaltılır.
299
300
  auto_extensions = 0
300
301
  max_auto = ctx.config.fetch("agent.goal_auto_continue_limit", 0).to_i
301
- while !res[:ok] && res[:error]&.include?("Max steps budget exceeded")
302
+ # Yapılandırılmış neden (loop.rb terminali): insan-okur string
303
+ # yalnız gösterim içindir — otomasyon prozu parse etmesin.
304
+ while !res[:ok] && res[:reason] == :budget_exhausted
302
305
  if auto_extensions < max_auto
303
306
  auto_extensions += 1
304
307
  ctx.out.puts "\n🤖 [Rubik::Goal] Adım bütçesi doldu (#{res[:error]}). " \
@@ -623,6 +626,14 @@ module Rubik
623
626
  shell.register_command("format", description: "Format target file", audience: :both) do |args, ctx|
624
627
  target = args.first
625
628
  if target
629
+ if ctx.agent_caller
630
+ begin
631
+ ctx.guard.verify_path_write!(target)
632
+ rescue Rubik::Security::BlockedWriteError => e
633
+ ctx.out.puts "Security Error: formatting critical path blocked: #{e.message}"
634
+ next
635
+ end
636
+ end
626
637
  lang = Rubik::Runtime::Discovery.detect_primary_language(Dir.pwd) || "ruby"
627
638
  adapter = ctx.adapter_registry.get(lang) || ctx.adapter_registry.get("ruby")
628
639
  res = adapter.format_code(target)
@@ -154,6 +154,10 @@ module Rubik
154
154
  ctx.out.puts " • Prompt Indicator : #{ctx.config.fetch('buffer.prompt_indicator', true)}"
155
155
  ctx.out.puts " • Reminder Interval: #{ctx.config.fetch('buffer.reminder_interval', 3)} turns"
156
156
  elsif ["manual", "on_test", "on_finish", "always"].include?(sub)
157
+ if ctx.agent_caller
158
+ ctx.out.puts "Security Error: buffer autoapply policy is operator-only and cannot be altered by autonomous agents."
159
+ return
160
+ end
157
161
  res = ctx.config.set("buffer.auto_apply", sub, persist: scope)
158
162
  return if Base.report_persist_failure(ctx, res, scope)
159
163
 
@@ -21,6 +21,11 @@ module Rubik
21
21
  scope, clean_args = Base.parse_scope(args)
22
22
  sub = clean_args.first&.downcase || "status"
23
23
 
24
+ if ctx.agent_caller && !["status", "list", "ping", "tools"].include?(sub)
25
+ ctx.out.puts "Security Error: MCP server management ('#{sub}') is operator-only and cannot be altered by autonomous agents."
26
+ next
27
+ end
28
+
24
29
  case sub
25
30
  when "status"
26
31
  status_servers(ctx, manager)
@@ -3,6 +3,7 @@
3
3
  require_relative "base"
4
4
  require_relative "../../orchestrator/subagent/budget"
5
5
  require_relative "../../orchestrator/subagent/notices"
6
+ require_relative "../../orchestrator/subagent/admission_policy"
6
7
 
7
8
  module Rubik
8
9
  module REPL
@@ -63,10 +64,11 @@ module Rubik
63
64
 
64
65
  ctx.out.puts "=== Subagent Process Hierarchy (#{instances.size} tracked, #{sup.active_count} active) ==="
65
66
  instances.each do |inst|
67
+ # A :spawning spec is mid-launch, not ended — ask spec vocabulary directly.
66
68
  dur = if inst.running?
67
69
  "up #{inst.uptime.round(1)}s"
68
- elsif inst.state == :queued
69
- "queued (waiting on: #{inst.depends_on.join(', ')})"
70
+ elsif inst.respond_to?(:spawning?) && (inst.queued? || inst.spawning?)
71
+ "queued/launching (waiting on: #{inst.depends_on.join(', ')})"
70
72
  else
71
73
  "ended (#{inst.uptime.round(1)}s)"
72
74
  end
@@ -104,10 +106,9 @@ module Rubik
104
106
  types = sup.type_registry.list
105
107
  ctx.out.puts "=== Available Subagent Archetypes (#{types.size}) ==="
106
108
  types.each do |t|
107
- flags = []
108
- flags << "write" if t.enable_write_tools
109
- flags << "nesting" if t.enable_subagent_tools
110
- flag_str = flags.empty? ? "read-only" : flags.join(", ")
109
+ label = Rubik::Orchestrator::Subagent::AdmissionPolicy.capability_label(t)
110
+ # Same capability vocabulary the prompt's tools= attribute uses.
111
+ flag_str = t.enable_subagent_tools ? "#{label}, nesting" : label
111
112
  ctx.out.puts " • #{t.name.ljust(12)} [#{flag_str}]: #{t.description}"
112
113
  end
113
114
  end
@@ -384,11 +384,31 @@ module Rubik
384
384
  "sandbox.",
385
385
  "subagents.",
386
386
  "plugins.",
387
- "lsp.servers.",
387
+ "lsp.",
388
+ "network.",
389
+ "mcp.",
390
+ "test.",
391
+ "linter.",
392
+ "project.test_command",
393
+ "adapter.",
394
+ "skills.paths",
395
+ "storage.root",
396
+ "buffer.model_can_apply",
397
+ "buffer.auto_apply",
388
398
  "workspace.allow_external_writes",
399
+ "workspace.allowed_external_dirs",
400
+ "workspace.additional_roots",
389
401
  "tools.circuit_breaker."
390
402
  ].freeze
391
403
 
404
+ def self.operator_only_config_key?(key)
405
+ k = key.to_s.strip
406
+ OPERATOR_ONLY_CONFIG_PREFIXES.any? do |p|
407
+ prefix = p.chomp(".")
408
+ k == prefix || k.start_with?("#{prefix}.")
409
+ end
410
+ end
411
+
392
412
  private_class_method def self.register_config_command(shell)
393
413
  shell.register_command("config", description: "Get, set, or view runtime configuration (set|get|list|path)",
394
414
  usage: USAGE_CONFIG, audience: :both) do |args, ctx|
@@ -417,7 +437,7 @@ module Rubik
417
437
  val = clean_args[2..]&.join(" ")
418
438
  if key.nil? || key.empty? || val.nil? || val.empty?
419
439
  ctx.out.puts "Usage: !config set <key> <val> [--project|--global]"
420
- elsif ctx.agent_caller && OPERATOR_ONLY_CONFIG_PREFIXES.any? { |p| key.start_with?(p) }
440
+ elsif ctx.agent_caller && operator_only_config_key?(key)
421
441
  # Security boundary: agents cannot alter security, sandbox, subagent governance,
422
442
  # plugins (arbitrary code execution), LSP binary commands, or external write policies.
423
443
  ctx.out.puts "Security Error: configuration key '#{key}' is operator-only and cannot be altered by autonomous agents."