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
@@ -12,10 +12,15 @@ module Rubik
12
12
  @monitor.synchronize { render_xml }
13
13
  end
14
14
 
15
+ def to_json(*_args)
16
+ @monitor.synchronize { Rubik::Platform.safe_json_generate(@doc) }
17
+ end
18
+
15
19
  # §4.1 render: GoalState#to_xml mold'u — tüm metin xml_escape'ten
16
20
  # geçer; boş koleksiyonların etiketi HİÇ basılmaz ("yokluk, boşluk
17
21
  # değil" kuralı); optional attribute'lar (storage_id, verify) yalnız
18
- # set iken basılır.
22
+ # set iken basılır; koleksiyon öğeleri RFC 6902 JSON-pointer adresi
23
+ # için açık `index` taşır.
19
24
  def render_xml
20
25
  esc = Rubik::Platform.method(:xml_escape)
21
26
  attrs = %(rev="#{@doc['rev']}")
@@ -23,36 +28,38 @@ module Rubik
23
28
  attrs += %( updated_at="#{@updated_at.utc.iso8601}") if @updated_at
24
29
  body = []
25
30
  body << %( <objective>#{esc.call(@doc['objective'].to_s)}</objective>)
26
- tasks = @doc["tasks"].map do |task|
31
+ tasks = @doc["tasks"].each_with_index.map do |task, idx|
27
32
  text = task["title"].to_s
28
33
  text += " — notes: #{task['notes']}" if task["notes"]
29
- attrs_t = %(id="#{esc.call(task['id'].to_s)}" status="#{esc.call(task['status'].to_s)}")
30
- attrs_t += %( verify="#{esc.call(task['verify'].to_s)}") if task["verify"]
34
+ attrs_t = %(id="#{esc.call(task['id'].to_s)}" status="#{esc.call(task['status'].to_s)}" index="#{idx}")
35
+ verify_val = task["verify"].is_a?(Hash) ? Rubik::Platform.safe_json_generate(task["verify"]) : task["verify"].to_s
36
+ attrs_t += %( verify="#{esc.call(verify_val)}") if task["verify"]
31
37
  task["title"] || task["notes"] ? %( <task #{attrs_t}>#{esc.call(text)}</task>) : %( <task #{attrs_t} />)
32
38
  end
33
39
  body << "<tasks>\n#{tasks.join("\n")}\n </tasks>" unless tasks.empty?
34
- findings = @doc["findings"].map do |f|
35
- %( <finding id="#{esc.call(f['id'].to_s)}" source_step="#{f['source_step']}">#{esc.call(f['text'].to_s)}</finding>)
40
+ findings = @doc["findings"].each_with_index.map do |f, idx|
41
+ %( <finding id="#{esc.call(f['id'].to_s)}" source_step="#{f['source_step']}" index="#{idx}">#{esc.call(f['text'].to_s)}</finding>)
36
42
  end
37
43
  body << "<findings>\n#{findings.join("\n")}\n </findings>" unless findings.empty?
38
- decisions = @doc["decisions"].map do |dec|
39
- attrs_d = %(id="#{esc.call(dec['id'].to_s)}")
44
+ decisions = @doc["decisions"].each_with_index.map do |dec, idx|
45
+ attrs_d = %(id="#{esc.call(dec['id'].to_s)}" index="#{idx}")
40
46
  attrs_d += %( rationale="#{esc.call(dec['rationale'].to_s)}") if dec["rationale"]
41
47
  %( <decision #{attrs_d}>#{esc.call(dec['text'].to_s)}</decision>)
42
48
  end
43
49
  body << "<decisions>\n#{decisions.join("\n")}\n </decisions>" unless decisions.empty?
44
- questions = @doc["open_questions"].map { |q| %( <question>#{esc.call(q.to_s)}</question>) }
50
+ questions = @doc["open_questions"].each_with_index.map { |q, idx| %( <question index="#{idx}">#{esc.call(q.to_s)}</question>) }
45
51
  body << "<open_questions>\n#{questions.join("\n")}\n </open_questions>" unless questions.empty?
46
- notes = @doc["environment_notes"].map do |note|
47
- attrs_n = %(id="#{esc.call(note['id'].to_s)}")
48
- attrs_n += %( verify="#{esc.call(note['verify'].to_s)}") if note["verify"]
52
+ notes = @doc["environment_notes"].each_with_index.map do |note, idx|
53
+ attrs_n = %(id="#{esc.call(note['id'].to_s)}" index="#{idx}")
54
+ verify_val = note["verify"].is_a?(Hash) ? Rubik::Platform.safe_json_generate(note["verify"]) : note["verify"].to_s
55
+ attrs_n += %( verify="#{esc.call(verify_val)}") if note["verify"]
49
56
  %( <note #{attrs_n}>#{esc.call(note['text'].to_s)}</note>)
50
57
  end
51
58
  body << "<environment_notes>\n#{notes.join("\n")}\n </environment_notes>" unless notes.empty?
52
59
  <<~XML.strip
53
- <goal_ledger #{attrs}>
60
+ <#{Prompt::ContextCompactor::GOAL_LEDGER_TAG} #{attrs}>
54
61
  #{body.join("\n")}
55
- </goal_ledger>
62
+ </#{Prompt::ContextCompactor::GOAL_LEDGER_TAG}>
56
63
  XML
57
64
  end
58
65
  end
@@ -2,6 +2,7 @@
2
2
 
3
3
  require "monitor"
4
4
  require "time"
5
+ require_relative "../events"
5
6
  require_relative "../platform"
6
7
 
7
8
  module Rubik
@@ -12,12 +13,13 @@ module Rubik
12
13
  # — okuma (read_file) her an güvenli olmalıdır.
13
14
  class GoalState
14
15
  # Bitiş olayının bus adı (Vakanüvis kronikçisinin goal kancası — K3;
15
- # REPL bu olaya abone değildir, notice/wake üretilmez).
16
- FINISH_EVENT = :goal_finished
16
+ # REPL bu olaya abone değildir, notice/wake üretilmez). İsim tek
17
+ # yaprakta: Rubik::Events (bağımlılıksız söz dağarcığı).
18
+ FINISH_EVENT = Rubik::Events::GOAL_FINISHED
17
19
  # Askı olayının bus adı (issue #106): transient transport hatası
18
20
  # goal'u terminal değil SUSPENDED'a götürür — kronikçi askıyı da
19
21
  # görsün; REPL yine abone değildir.
20
- SUSPEND_EVENT = :goal_suspended
22
+ SUSPEND_EVENT = Rubik::Events::GOAL_SUSPENDED
21
23
 
22
24
  def initialize(event_bus: nil)
23
25
  @monitor = Monitor.new
@@ -87,15 +89,6 @@ module Rubik
87
89
  self
88
90
  end
89
91
 
90
- def record_tokens!(usage)
91
- @monitor.synchronize do
92
- u = usage.to_h
93
- @tokens[:input] += u[:input].to_i
94
- @tokens[:output] += u[:output].to_i
95
- end
96
- self
97
- end
98
-
99
92
  def complete!(output_summary = nil, tokens: nil)
100
93
  @monitor.synchronize do
101
94
  return self unless @status == :running
@@ -138,9 +131,16 @@ module Rubik
138
131
  return self unless @status == :running
139
132
 
140
133
  @last_error = Rubik::Platform.safe_utf8(reason.to_s).slice(0, 300)
141
- t = tokens.to_h
142
- @tokens[:input] += t[:input].to_i
143
- @tokens[:output] += t[:output].to_i
134
+ if tokens
135
+ # Mutlak atama (restore_counters! moldu): Loop'un kümülatif
136
+ # token sayacı SSOT'tur. += askı→resume→askı döngüsünde ilk
137
+ # askının kullanımını iki kez sayardı — mutlak atama idempotent
138
+ # kalır ve Σ damgasıyla hep aynı değeri taşır. tokens: nil
139
+ # mevcut değerleri korur (sayaç korunumu sözleşmesi).
140
+ t = tokens.to_h
141
+ @tokens = { input: (t[:input] || t["input"]).to_i,
142
+ output: (t[:output] || t["output"]).to_i }
143
+ end
144
144
  @status = :suspended
145
145
  end
146
146
  notify_suspend
@@ -77,6 +77,7 @@ module Rubik
77
77
  @subagent_notice_inbox = SubagentNoticeInbox.new
78
78
  @goal_mode = false
79
79
  @goal_wait = nil
80
+ @last_prompt_fingerprint = nil
80
81
  end
81
82
 
82
83
  # §7.2 item 3 (ContinuationManager mold): the notice queue lives in
@@ -95,9 +96,7 @@ module Rubik
95
96
 
96
97
  # The merge policy lives in Prompt::ConversationRows (the row-dialect
97
98
  # single home, shared with the REPL injector and the compaction layer).
98
- def merge_notice_block_into_history!(xml_payload)
99
- Prompt::ConversationRows.append_notice!(@history, xml_payload)
100
- end
99
+ def merge_notice_block_into_history!(xml_payload) = Prompt::ConversationRows.append_notice!(@history, xml_payload)
101
100
 
102
101
  def subagent_notice_inbox = (@subagent_notice_inbox ||= SubagentNoticeInbox.new)
103
102
 
@@ -106,14 +105,8 @@ module Rubik
106
105
  # test doubles — which skip initialize — answer goal_mode? false and
107
106
  # never build the collaborator off a nil @shell_deps.
108
107
  def goal_mode? = @goal_mode == true
109
-
110
- def goal_wait
111
- @goal_wait ||= GoalWait.new(@shell_deps)
112
- end
113
-
114
- def continuation_manager
115
- @continuation_manager ||= ContinuationManager.new(config: @config)
116
- end
108
+ def goal_wait = (@goal_wait ||= GoalWait.new(@shell_deps))
109
+ def continuation_manager = (@continuation_manager ||= ContinuationManager.new(config: @config))
117
110
 
118
111
  # Agent-turn-executor plan: response processing is shared with the
119
112
  # subagent channel through TurnExecutor; Loop supplies the
@@ -121,9 +114,7 @@ module Rubik
121
114
  # initialize: several test doubles construct loops via
122
115
  # Class#allocate + instance_variable_set (build_knob_loop), which
123
116
  # skips initialize.
124
- def turn_executor
125
- @turn_executor ||= TurnExecutor.new(channel: TurnExecutor::UserChannel.new(self))
126
- end
117
+ def turn_executor = (@turn_executor ||= TurnExecutor.new(channel: TurnExecutor::UserChannel.new(self)))
127
118
 
128
119
  def extend_budget(extra_steps) = (@max_steps += extra_steps.to_i)
129
120
 
@@ -150,11 +141,7 @@ module Rubik
150
141
  opts = target_model ? { model: target_model } : {}
151
142
  opts[:tools] = @tool_registry.schemas unless plan_only
152
143
 
153
- mode = if plan_only
154
- :plan
155
- else
156
- goal_mode ? :goal : :default
157
- end
144
+ mode = loop_mode(plan_only, goal_mode)
158
145
 
159
146
  # Prompt view built once at the composition boundary: the
160
147
  # orchestrator resolves coeffects (skills index, type registry)
@@ -165,16 +152,12 @@ module Rubik
165
152
  formatted_task = Rubik::Prompt::ContextBuilder.format_user_task(task_prompt)
166
153
 
167
154
  @history << { role: "system", content: system_prompt }
155
+ @last_prompt_fingerprint = prompt_state_fingerprint(plan_only: plan_only)
168
156
 
169
- # Inject prior dialogue turns if provided
170
- if conversation_history && !conversation_history.empty?
171
- conversation_history.each do |turn|
172
- r = turn[:role] || turn["role"]
173
- c = turn[:content] || turn["content"]
174
- next if r.nil? || c.nil? || c.to_s.strip.empty?
175
-
176
- @history << { role: r.to_s, content: c.to_s }
177
- end
157
+ # Inject prior dialogue turns if provided (sanitized against unauthorized system injection and unescaped pin tags)
158
+ Array(conversation_history).each do |turn|
159
+ sanitized = Prompt::ConversationRows.sanitize_dialogue_turn(turn)
160
+ @history << sanitized if sanitized
178
161
  end
179
162
 
180
163
  Rubik::Storage::Vakanuvis::Orientation.inject_session_start!(@history, @runtime_manager, config: @config)
@@ -200,11 +183,7 @@ module Rubik
200
183
  # appending to @history.last may target a tool result or a
201
184
  # content-less assistant message, which provider formatters then
202
185
  # mangle.
203
- approval = if auto
204
- "Step budget auto-extended (unattended continuation, agent.goal_auto_continue_limit)."
205
- else
206
- "User approved extending step budget by #{extra_steps} steps."
207
- end
186
+ approval = auto ? "Step budget auto-extended (unattended continuation, agent.goal_auto_continue_limit)." : "User approved extending step budget by #{extra_steps} steps."
208
187
  continuation_msg = "<step_budget_extended extra=\"#{extra_steps}\" new_max=\"#{@max_steps}\" " \
209
188
  "current=\"#{@step_count}\" auto=\"#{auto}\" " \
210
189
  "message=\"#{approval} " \
@@ -247,6 +226,7 @@ module Rubik
247
226
  @loop_context = @runtime_manager&.context&.extend
248
227
  begin
249
228
  @history << { role: "system", content: render_system_prompt(mode: :goal, plan_only: false, extra_context: nil) }
229
+ @last_prompt_fingerprint = prompt_state_fingerprint(plan_only: false)
250
230
  @history << { role: "user", content: Rubik::Prompt::ContextBuilder.format_user_task(goal_text) }
251
231
  @history << { role: "user", content: ledger.to_xml }
252
232
  append_resume_marker!(reason: reason, suspended_at: suspended_at, attempt: attempt)
@@ -286,6 +266,12 @@ module Rubik
286
266
 
287
267
  private
288
268
 
269
+ def loop_mode(plan_only, goal)
270
+ return :plan if plan_only
271
+
272
+ goal ? :goal : :default
273
+ end
274
+
289
275
  # run() ile resume_from'un paylaşımlı prompt-view üretimi (candidate 2
290
276
  # Phase 2 sözleşmesi): orchestrator coeffect'leri çözer, prompt
291
277
  # katmanı yalnız render eder. run()'ın eski satır içi gövdesi birebir.
@@ -298,13 +284,35 @@ module Rubik
298
284
  root_dir: @root_dir,
299
285
  extra_context: extra_context)
300
286
  Rubik::Prompt::ContextBuilder.build_system_prompt(
301
- mode: mode,
302
- tool_schemas: plan_only ? [] : @tool_registry.schemas,
303
- native_tools: !plan_only,
304
- services: services
287
+ mode: mode, tool_schemas: plan_only ? [] : @tool_registry.schemas,
288
+ native_tools: !plan_only, services: services
305
289
  )
306
290
  end
307
291
 
292
+ # Lightweight fingerprint of environment factors that affect the rendered system prompt.
293
+ # Preserves prompt caching by avoiding regeneration when state is unchanged.
294
+ def prompt_state_fingerprint(plan_only: false)
295
+ tools = plan_only ? [] : (@tool_registry&.schemas&.map { |s| s[:name] || s["name"] } || [])
296
+ skills = Rubik::Coeffects.get(@runtime_manager&.context, Rubik::Coeffects::SKILL_MANAGER)&.prompt_index
297
+ subagents = resolve_type_registry.list.map { |t| t.respond_to?(:name) ? t.name : t.to_s } if resolve_type_registry.respond_to?(:list)
298
+ dirty = @buffer_manager.dirty_files if @buffer_manager.respond_to?(:dirty_files)
299
+ dirty = dirty.is_a?(Hash) ? dirty.keys : Array(dirty)
300
+ lsp_diags = @lsp_manager.respond_to?(:all_diagnostics) ? @lsp_manager.all_diagnostics.size : 0
301
+ [tools, skills, subagents, dirty, lsp_diags].hash
302
+ end
303
+
304
+ # Dynamically updates @history[0] in-place if tools, skills, subagents, dirty files or LSP
305
+ # change mid-execution. Keeps prompt cache intact on zero-change steps.
306
+ def refresh_system_prompt_if_needed!(mode:, plan_only:, extra_context: nil)
307
+ return unless @history&.first && Prompt::ConversationRows.role_of(@history.first) == "system"
308
+ return if (current_fp = prompt_state_fingerprint(plan_only: plan_only)) == @last_prompt_fingerprint
309
+
310
+ @history.first[Prompt::ConversationRows.content_key_of(@history.first)] = render_system_prompt(mode: mode, plan_only: plan_only, extra_context: extra_context)
311
+ @last_prompt_fingerprint = current_fp
312
+ rescue StandardError => e
313
+ Rubik::Log.warn(:orchestrator, "system prompt refresh failed (#{e.class}: #{e.message}); keeping previous system prompt")
314
+ end
315
+
308
316
  # continue_loop'un opts sözleşmesinin aynısı: model override'ı yok —
309
317
  # resume, koşunun başındaki modeliyle sürer.
310
318
  def resume_request_opts
@@ -336,13 +344,10 @@ module Rubik
336
344
  secs = [(Time.now - suspended_at).to_i, 0].max
337
345
  mm, ss = secs.divmod(60)
338
346
  hh, mm = mm.divmod(60)
339
- if hh.positive?
340
- "#{hh}h #{mm.to_s.rjust(2, '0')}m"
341
- elsif mm.positive?
342
- "#{mm}m #{ss.to_s.rjust(2, '0')}s"
343
- else
344
- "#{ss}s"
345
- end
347
+ return "#{hh}h #{mm.to_s.rjust(2, '0')}m" if hh.positive?
348
+ return "#{mm}m #{ss.to_s.rjust(2, '0')}s" if mm.positive?
349
+
350
+ "#{ss}s"
346
351
  end
347
352
 
348
353
  def restore_resume_counters!(counters)
@@ -357,13 +362,8 @@ module Rubik
357
362
  # (review Öneri 3). Loop keeps thin private delegates with the
358
363
  # original names/signatures so call sites and send()-based tests are
359
364
  # untouched.
360
- def provider_registry_key
361
- provider_resolver.registry_key
362
- end
363
-
364
- def provider_llm_config(key, default)
365
- provider_resolver.llm_config(key, default)
366
- end
365
+ def provider_registry_key = provider_resolver.registry_key
366
+ def provider_llm_config(key, default) = provider_resolver.llm_config(key, default)
367
367
 
368
368
  # Built lazily on first use, NOT in initialize: several test doubles
369
369
  # construct loops via Class#allocate + instance_variable_set
@@ -372,9 +372,7 @@ module Rubik
372
372
  # safe: the provider reference is immutable for the loop's lifetime
373
373
  # and the config object is held by reference (values re-read per
374
374
  # fetch — config reactivity preserved).
375
- def provider_resolver
376
- @provider_resolver ||= ProviderResolver.new(provider: @provider, config: @config)
377
- end
375
+ def provider_resolver = (@provider_resolver ||= ProviderResolver.new(provider: @provider, config: @config))
378
376
 
379
377
  def resolve_type_registry
380
378
  if @runtime_manager&.context.respond_to?(:get)
@@ -400,6 +398,7 @@ module Rubik
400
398
  drain_subagent_notices_into_history!
401
399
  @step_count += 1
402
400
 
401
+ refresh_system_prompt_if_needed!(mode: loop_mode(plan_only, goal_mode?), plan_only: plan_only)
403
402
  warned = @budget_manager.evaluate_step_budget_warning!(warned)
404
403
  verify_goal_ledger! if goal_mode?
405
404
  @budget_manager.evaluate_context_compaction!
@@ -422,7 +421,7 @@ module Rubik
422
421
  return result if result
423
422
  end
424
423
 
425
- { ok: false, error: "Max steps budget exceeded (#{@max_steps})", steps: @step_count, tokens: @total_tokens, loop_instance: self }
424
+ { ok: false, error: "Max steps budget exceeded (#{@max_steps})", reason: :budget_exhausted, steps: @step_count, tokens: @total_tokens, loop_instance: self }
426
425
  end
427
426
 
428
427
  # Goal-ledger adım-baı yenilemesi (goal-ledger planı A): compaction
@@ -435,10 +434,14 @@ module Rubik
435
434
  # execute_steps iterasyonudur, bu yüzden doğrudan hook. Hata
436
435
  # izolasyonu: doğrulama asla akışı bozmaz.
437
436
  def verify_goal_ledger!
438
- Rubik::Orchestrator::GoalLedger::Verifier.at_step_boundary!(self)
437
+ # Coeffect çözümü çağıranındır: Verifier Loop'un iç yüzünü tanımaz.
438
+ ledger = Rubik::Coeffects.get(@runtime_manager&.context, Rubik::Coeffects::GOAL_LEDGER)
439
+ return unless ledger
440
+
441
+ Rubik::Orchestrator::GoalLedger::Verifier.verify!(ledger, trigger: :step, root_dir: @root_dir, config: @config)
439
442
  rescue StandardError => e
440
- # Dürüst kanal (Log.warn): debug_warn ENV-gated no-op'tur — doğrulama
441
- # çöktüğünde drift tespiti sessizce duramaz (sessiz-yutma yasağı).
443
+ # Dürüst kanal (Log.warn): doğrulama çöktüğünde drift tespiti
444
+ # sessizce duramaz (sessiz-yutma yasağı; debug_warn ENV-gated no-op).
442
445
  Rubik::Log.warn(:orchestrator, "goal ledger verification failed (#{e.class}: #{e.message}); step continues unverified")
443
446
  end
444
447
 
@@ -450,11 +453,7 @@ module Rubik
450
453
  end
451
454
 
452
455
  def send_llm_request_with_recovery(opts)
453
- streaming_enabled = if opts.key?(:stream)
454
- opts[:stream] == true
455
- else
456
- provider_llm_config("stream", true) != false
457
- end
456
+ streaming_enabled = opts.key?(:stream) ? (opts[:stream] == true) : (provider_llm_config("stream", true) != false)
458
457
 
459
458
  # Plan 61 D-1/D-3: the wire request must share the compaction math's
460
459
  # assumptions. Ollama needs context_limit (sent as num_ctx) or its
@@ -1,5 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "../tools/catalog"
4
+
3
5
  module Rubik
4
6
  module Orchestrator
5
7
  # Gerçek zamanlı LSP tampon-tanı geri beslemesi (Plan 56 D-5) —
@@ -10,7 +12,11 @@ module Rubik
10
12
  module LspFeedback
11
13
  module_function
12
14
 
13
- WRITER_TOOLS = ["write_file", "replace_file_content"].freeze
15
+ # Writers whose success lands exactly one file at args["path"] in the
16
+ # buffer — declared per tool (buffer_sync_writer:) and projected by
17
+ # Catalog, not the wider write-grant set (apply_buffer is multi-file;
18
+ # run_command/storage carry no path).
19
+ WRITER_TOOLS = Rubik::Tools::Catalog.buffer_sync_writers
14
20
 
15
21
  def refresh(deps:, tool_instance:, tool_args:, tool_result:)
16
22
  return tool_result unless tool_result.status == :ok
@@ -0,0 +1,161 @@
1
+ # frozen_string_literal: true
2
+
3
+ # No require of tools/catalog here: this file is loaded from inside the
4
+ # tools/builtins require chain (via profile_contract), and Catalog must not
5
+ # be re-entered mid-load. Every requiring module (scoped_registry,
6
+ # builtin_types) already requires catalog itself, and all Catalog reads
7
+ # happen at call time.
8
+ module Rubik
9
+ module Orchestrator
10
+ module Subagent
11
+ # Single home for "what does plane P get?": the dynamic-origin vocabulary,
12
+ # the risk ladder, the per-plane admission rule, and the capability labels
13
+ # derived from the same rule. ScopedRegistry stays the executor; the
14
+ # built-in archetypes and ProfileContract delegate here so the filters and
15
+ # the labels the prompt prints cannot drift apart.
16
+ module AdmissionPolicy
17
+ module_function
18
+
19
+ # Dynamic-tool origins: on every plane they answer to the risk ladder,
20
+ # same as unknown future origins — the builtin name rule is builtin-only.
21
+ DYNAMIC_ORIGINS = [:synthesis, :overlay].freeze
22
+ MCP = :mcp
23
+ RISK_LADDER = [:read, :write, :execute].freeze
24
+
25
+ LABEL_FULL_CLONE = "full_clone"
26
+ LABEL_READ_WRITE_TEST = "read_write_test"
27
+ LABEL_READ_EXECUTE = "read_execute"
28
+ LABEL_READ_ONLY = "read_only"
29
+
30
+ # One risk-reading idiom for every consumer. Unknown (missing or
31
+ # unrecognized) risk normalizes to nil, which no ladder admits —
32
+ # admission fails closed everywhere.
33
+ def risk_of(tool)
34
+ tool.respond_to?(:risk) ? tool.risk.to_s.downcase.to_sym : nil
35
+ end
36
+
37
+ # The self archetype is the full-clone plane (its name is reserved, so
38
+ # no custom type can collide with it). Every other arity-1-filtered
39
+ # type lands on the custom plane: its own filter governs builtin names,
40
+ # and this policy governs dynamic and MCP origins on top.
41
+ def plane_for(type_def)
42
+ self_plane?(type_def) ? :self : type_def
43
+ end
44
+
45
+ def self_plane?(type_def)
46
+ type_def.respond_to?(:name) && type_def.name.to_s.downcase.strip == "self"
47
+ end
48
+
49
+ # A malformed plane would otherwise fall into the custom rule and
50
+ # silently admit the full builtin catalog — fail loud instead.
51
+ def allowed?(name, tool, origin, plane:)
52
+ return false if Rubik::Tools::Catalog.orchestrator_only_tools.include?(name.to_s)
53
+ unless plane == :research || plane == :coder || plane == :self ||
54
+ (plane.respond_to?(:tool_filter) && plane.respond_to?(:name))
55
+ raise ArgumentError,
56
+ "unknown admission plane #{plane.inspect}; pass :research, :coder, :self or a subagent type_def"
57
+ end
58
+
59
+ case plane
60
+ when :research then research_admits?(name, tool, origin)
61
+ when :coder then coder_admits?(name, tool, origin)
62
+ when :self then self_admits?(tool, origin)
63
+ else custom_admits?(tool, origin, write_grant?(plane))
64
+ end
65
+ end
66
+
67
+ # Name-level grants formula for custom types over the builtin catalog.
68
+ # The origin/risk gate is not folded in here: the executor applies it
69
+ # through allowed? so one idiom covers every arity-1-filtered plane.
70
+ def custom_tool_filter(grants)
71
+ enabled = grants.dup.freeze
72
+ write_tools = Rubik::Tools::Catalog.write_grant_tools
73
+ spawn_tools = Rubik::Tools::Catalog.spawn_tools
74
+
75
+ lambda do |tool_name|
76
+ next false if write_tools.include?(tool_name) && !enabled.include?("write")
77
+ next false if spawn_tools.include?(tool_name) && !enabled.include?("subagent_spawn")
78
+
79
+ true
80
+ end
81
+ end
82
+
83
+ # Capability label for the plane's admitted toolset, simulated over the
84
+ # builtin catalog with the type's own filter — the same predicate the
85
+ # executor gates runtime admission with.
86
+ def capability_label(type_def)
87
+ return LABEL_FULL_CLONE if self_plane?(type_def)
88
+
89
+ declarations = admitted_builtin_declarations(type_def)
90
+ return LABEL_READ_WRITE_TEST if declarations.any?(&:write_grant?)
91
+ return LABEL_READ_EXECUTE if declarations.any? { |declaration| risk_of(declaration) == :execute }
92
+
93
+ LABEL_READ_ONLY
94
+ end
95
+
96
+ # Builtin-origin tools follow the plane's name rule; every other
97
+ # origin (dynamic or unknown) answers to the risk ladder — a future
98
+ # origin can never ride a builtin name past the risk rules.
99
+ def research_admits?(name, tool, origin)
100
+ return false if origin == MCP
101
+ return Rubik::Tools::Catalog.research_tools.include?(name.to_s) if builtin_origin?(origin)
102
+
103
+ risk_of(tool) == :read
104
+ end
105
+
106
+ def coder_admits?(name, tool, origin)
107
+ return false if origin == MCP
108
+ return Rubik::Tools::Catalog.coder_tools.include?(name.to_s) if builtin_origin?(origin)
109
+
110
+ RISK_LADDER.include?(risk_of(tool))
111
+ end
112
+
113
+ def self_admits?(tool, origin)
114
+ return true if builtin_origin?(origin)
115
+
116
+ RISK_LADDER.include?(risk_of(tool))
117
+ end
118
+
119
+ def custom_admits?(tool, origin, write_grant)
120
+ return true if builtin_origin?(origin)
121
+
122
+ risk = risk_of(tool)
123
+ return false unless RISK_LADDER.include?(risk)
124
+
125
+ risk == :read || write_grant
126
+ end
127
+
128
+ # Only the builtin catalog default-allows. Every real, non-builtin
129
+ # origin — known-dynamic, MCP, or a future one — is ladder-gated so a
130
+ # new origin can never bypass the risk rules. nil origin is the
131
+ # registration idiom's implicit builtin.
132
+ def builtin_origin?(origin)
133
+ origin.nil? || origin == :builtin
134
+ end
135
+
136
+ def write_grant?(type_def)
137
+ return true if type_def.respond_to?(:enable_write_tools) && type_def.enable_write_tools
138
+ return false unless type_def.respond_to?(:grants)
139
+
140
+ Array(type_def.grants).include?("write")
141
+ end
142
+
143
+ def admitted_builtin_declarations(type_def)
144
+ filter = type_def.respond_to?(:tool_filter) ? type_def.tool_filter : nil
145
+ unless filter
146
+ raise ArgumentError,
147
+ "type '#{type_def.name}' carries no tool_filter; the capability label cannot simulate admission"
148
+ end
149
+
150
+ root_only = Rubik::Tools::Catalog.orchestrator_only_tools
151
+ Rubik::Tools::Catalog.names
152
+ .select { |name| !root_only.include?(name) && filter.call(name) }
153
+ .filter_map { |name| Rubik::Tools::Catalog[name] }
154
+ end
155
+
156
+ private_class_method :self_plane?, :research_admits?, :coder_admits?, :self_admits?,
157
+ :custom_admits?, :builtin_origin?, :write_grant?, :admitted_builtin_declarations
158
+ end
159
+ end
160
+ end
161
+ end
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "../../tools/catalog"
4
+ require_relative "admission_policy"
4
5
 
5
6
  module Rubik
6
7
  module Orchestrator
@@ -38,7 +39,7 @@ module Rubik
38
39
  "4. Assumptions & Notes: Concrete limitations or next steps. " \
39
40
  "Do NOT call ask_question for routine uncertainties — infer from codebase context and document assumptions under Assumptions & Notes. " \
40
41
  "If the investigation is fundamentally blocked, ask the maestro with the ask_question tool.",
41
- tool_filter: ->(name) { READ_ONLY_TOOLS.include?(name) },
42
+ tool_filter: ->(name, tool = nil, origin = nil) { AdmissionPolicy.allowed?(name, tool, origin, plane: :research) },
42
43
  enable_write_tools: false, enable_subagent_tools: false
43
44
  ),
44
45
  type_def_class.new(
@@ -67,7 +68,7 @@ module Rubik
67
68
  "Do NOT call ask_question for routine implementation choices or minor ambiguities — make standard engineering assumptions " \
68
69
  "aligned with existing codebase patterns and document them under Assumptions & Notes. " \
69
70
  "If a requirement is fundamentally contradictory, ask the maestro with the ask_question tool.",
70
- tool_filter: ->(name) { CODER_TOOLS.include?(name) },
71
+ tool_filter: ->(name, tool = nil, origin = nil) { AdmissionPolicy.allowed?(name, tool, origin, plane: :coder) },
71
72
  enable_write_tools: true, enable_subagent_tools: false
72
73
  ),
73
74
  type_def_class.new(
@@ -19,9 +19,22 @@ module Rubik
19
19
  # this spec — nil for explicitly detached work. A cancelled owner makes
20
20
  # the claim loops drop the spec before it ever starts.
21
21
  class DeferredSpec
22
+ class StateError < StandardError; end
23
+
24
+ # The spec machine's every legal from->to edge (Lifecycle family
25
+ # doctrine: one guarded transition per state machine, fail-loud on
26
+ # undeclared edges, same-state idempotent). :cancelled is absorbing —
27
+ # a cancelled spec never re-queues (requeue! refuses) and never
28
+ # re-launches (the claim loops skip it).
29
+ TRANSITIONS = {
30
+ queued: [:spawning, :cancelled],
31
+ spawning: [:queued, :cancelled],
32
+ cancelled: []
33
+ }.transform_values(&:freeze).freeze
34
+
22
35
  attr_reader :id, :parent_id, :role, :type_name, :prompt, :system_prompt,
23
- :workspace, :model, :max_steps, :deps, :provider, :owner
24
- attr_accessor :state, :cancel_reason
36
+ :workspace, :model, :max_steps, :deps, :provider, :owner,
37
+ :state, :cancel_reason
25
38
 
26
39
  def initialize(id:, role:, prompt:, type_name:, deps:, parent_id: ConversationId::ROOT_ID, system_prompt: nil,
27
40
  workspace: "inherit", model: "inherit", max_steps: nil, provider: nil, owner: nil)
@@ -45,6 +58,27 @@ module Rubik
45
58
  def spawning? = @state == :spawning
46
59
  def cancelled? = @state == :cancelled
47
60
 
61
+ # The only mutators (Lifecycle family): the dependency engine claims
62
+ # with mark_spawning!, re-queues a concurrency-refused launch with
63
+ # requeue!, and cancels with cancel! — first reason wins, exactly
64
+ # like TaskCancellation#cancel!. Same-state writes are idempotent
65
+ # no-ops; anything else undeclared raises StateError.
66
+ def mark_spawning!
67
+ transition!(:spawning)
68
+ end
69
+
70
+ def requeue!
71
+ transition!(:queued) unless cancelled?
72
+ end
73
+
74
+ def cancel!(reason)
75
+ return false if cancelled?
76
+
77
+ @cancel_reason = reason.to_s
78
+ transition!(:cancelled)
79
+ true
80
+ end
81
+
48
82
  # Duck-type yüzeyi: render'lar (list/status/wait) Instance ile
49
83
  # DeferredSpec'i AYIRT ETMEDEN kullanır — dallanma yok.
50
84
  def running? = false
@@ -70,6 +104,21 @@ module Rubik
70
104
  started_at: nil, ended_at: nil, transcript: nil, last_error: @cancel_reason,
71
105
  result_summary: nil, result: nil, detached: @owner.nil? }
72
106
  end
107
+
108
+ private
109
+
110
+ # Guarded low-level seam (mirrors Lifecycle#transition!): business
111
+ # callers use the named drivers; illegal edges fail loud with both
112
+ # endpoints in the message. No own lock — every writer already holds
113
+ # the supervisor monitor.
114
+ def transition!(to)
115
+ target = to.to_sym
116
+ return @state if @state == target
117
+
118
+ raise StateError, "illegal DeferredSpec transition #{@id}: #{@state} -> #{target}" unless TRANSITIONS.fetch(@state, []).include?(target)
119
+
120
+ @state = target
121
+ end
73
122
  end
74
123
  end
75
124
  end