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
@@ -1,31 +1,39 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "monitor"
4
+ require_relative "../../concurrency"
5
+ require_relative "../../events"
4
6
 
5
7
  module Rubik
6
8
  module Storage
7
9
  module Vakanuvis
8
- # Düzlem 1 — Deterministik Çekirdek: tek worker thread + sınırlı FIFO kuyruk.
9
- # Olay kapıları mevcut bus abonelikleridir (subagent tamamlanma + goal
10
- # bitişi — K3); NE ZAMAN, NEREYE, NASIL yazılacağı burada kural tabanlıdır.
10
+ # Düzlem 1 — Deterministik Çekirdek: tek worker thread + sınırlı FIFO
11
+ # kuyruk (Concurrency::Worker iskeleti: atomik kabul, idempotent
12
+ # kapanış, busy sayımı ve son-çare ağı iskelettedir). Olay kapıları
13
+ # mevcut bus abonelikleridir (subagent tamamlanma + goal bitişi — K3);
14
+ # NE ZAMAN, NEREYE, NASIL yazılacağı burada kural tabanlıdır.
11
15
  # Sessizlik sözleşmesi (§4.3): WAKE_KINDS dışında kalır, notice yaymaz —
12
16
  # sadece dmesg/stderr. Ömür: ctx dispose'u LIFO ile kapatır (worker kill + abonelik geri alımı).
13
17
  class Harness
14
- STOP = :__vakanuvis_stop__
18
+ include Concurrency::Worker
19
+
20
+ # STOP işareti iskeletin tek ev sahibinde; sabit adı kuyruk gözetimi
21
+ # ve test ikizleri için yaşar.
22
+ STOP = Concurrency::Worker::STOP
15
23
  MAX_QUEUE = 200
16
24
  # v2 §4-V4: damıtıcı kaynak disiplini — yalnız TAMAMLANMIŞ transcript'ler,
17
25
  # damıtıcının kendisi Hariç (özyineleme kirliliği: canlı depoda transcript satırları 'vakanuvis' etiketi taşır).
18
26
  SOURCE_TRANSCRIPT_LIMIT = 8
19
- # Literaller, depolama katmanını orchestrator require'larından
20
- # uzak tutar; test ikizleri her ikisini de sabitlere pinler:
21
- # Notices::COMPLETED_EVENT ve GoalState::FINISH_EVENT. TURN_EVENT,
22
- # REPL TurnRecorder#emit_turn_finished kapısıdır (root-turn planı 2026-10-04).
23
- SUBAGENT_EVENT = :subagent_completed
24
- GOAL_EVENT = :goal_finished
25
- TURN_EVENT = :turn_finished
26
- # Askı kroniği (tarama kartı 2, 2026-11-01): GoalState::SUSPEND_EVENT — abonelik
27
- # :goal akışına yazar; worker status=="suspended" ile ayırt eder.
28
- SUSPEND_EVENT = :goal_suspended
27
+ # Olay adları Rubik::Events yaprağından okunur: yaprak sıfır
28
+ # require'lıdır (uris.rb gramer yaprağı öncülü) — depolama
29
+ # katmanı orchestrator mantığına bağımlı olmadan tek söz
30
+ # dağarcığına bağlanır; izolasyon doktrininin harfi bozulmaz.
31
+ SUBAGENT_EVENT = Rubik::Events::SUBAGENT_COMPLETED
32
+ GOAL_EVENT = Rubik::Events::GOAL_FINISHED
33
+ TURN_EVENT = Rubik::Events::TURN_FINISHED
34
+ # Askı kroniği: abonelik :goal akışına yazar; worker
35
+ # status=="suspended" ile ayırt eder.
36
+ SUSPEND_EVENT = Rubik::Events::GOAL_SUSPENDED
29
37
 
30
38
  attr_reader :store, :config, :supervisor, :dmesg, :session_slug, :gate
31
39
 
@@ -74,61 +82,19 @@ module Rubik
74
82
  self
75
83
  end
76
84
 
77
- def stopped? = @monitor.synchronize { @stopped }
78
-
79
- # Dispose yolu: FIFO'daki her şey (STOP dahil öncesindeki olaylar) işlenir,
80
- # sonra thread sonlanır. Kalan olay yarımda kalmaz; thread 2 saniyede durmazsa
81
- # (yavaş bir flush/spawn içinde) kill gelir ve işlenemeyen olay sayısı dmesg'e düşer — sessiz kayıp yok.
82
- def shutdown
83
- @monitor.synchronize do
84
- return if @stopped
85
-
86
- @stopped = true
87
- @busy += 1 # STOP işaretinin de işleniş sayılır
88
- @queue.push(STOP)
89
- end
90
- begin
91
- auto_digest_touched!(spawn: false)
92
- rescue StandardError => e
93
- Vakanuvis.log_via(@dmesg, :warn, "shutdown auto-digest failed (#{e.class}: #{e.message}) — worker teardown continues")
94
- end
95
- @worker&.join(2)
96
- if @worker&.alive?
97
- Vakanuvis.log_via(@dmesg, :warn, "worker did not stop in 2s — killing with #{queue_size} event(s) unprocessed")
98
- @worker.kill
99
- end
100
- @worker = nil
101
- end
102
-
103
- def wait_idle(timeout: 2.0)
104
- deadline = Time.now + timeout
105
- sleep 0.01 while busy? && Time.now < deadline
106
- !busy?
107
- end
108
-
109
- # Kuyrukta + uçuştaki olay sayısı (push'ta artar, işlenince/düşürülünce azalır) — pop ile işaretleme arasındaki yarış penceresini kapatır.
110
- def busy? = @monitor.synchronize { @busy.positive? }
111
-
112
85
  # ---- olay giriş kapıları (kworker thread'inde çağrılır) -----------
113
86
 
87
+ # Atomik kabul (stopped-kontrol + push tek kritik bölümde) iskelette:
88
+ # kapanış yarışındaki olay ya STOP'tan önce düşer ve işlenir ya da
89
+ # reddedilir — arada kalan işleyeneksiz olay kalamaz.
114
90
  def enqueue_event(kind, payload)
115
91
  unless payload.is_a?(Hash)
116
92
  Vakanuvis.log_via(@dmesg, :warn, "discarded non-hash #{kind} event (#{payload.class})")
117
93
  return false
118
94
  end
119
-
120
- @monitor.synchronize do
121
- return false if @stopped
122
-
123
- drop_oldest! if @queue.size >= @max_queue
124
- @busy += 1
125
- @queue.push([kind, payload])
126
- true
127
- end
95
+ super
128
96
  end
129
97
 
130
- def queue_size = @queue.size
131
-
132
98
  # ---- talep düzlemi (maestro aracı buraya delege eder; K7) ---------
133
99
 
134
100
  # Deterministik geri çağırma Recall düzleminde (recall.rb); burada
@@ -215,37 +181,31 @@ module Rubik
215
181
  @event_bus.subscribe(TURN_EVENT, context: @context) { |p| enqueue_event(:turn, p) } if @root_turns
216
182
  end
217
183
 
218
- # Taşma düşürmesi asla STOP işaretini yutamaz (yutsa worker hiç
219
- # sonlanamazdı): STOP geldiyse kuyruğun sonuna geri konur.
220
- def drop_oldest!
221
- item = @queue.pop(true)
222
- if item == STOP
223
- @queue.push(STOP)
224
- else
225
- @monitor.synchronize do
226
- @dropped += 1
227
- @busy -= 1
228
- end
229
- Vakanuvis.log_via(@dmesg, :warn, "event queue overflow — dropped oldest (total: #{@dropped})")
230
- end
231
- rescue ThreadError
232
- nil
184
+ # ---- Concurrency::Worker iskelet kancaları --------------------------
185
+
186
+ def worker_max_queue = @max_queue
187
+
188
+ def worker_warn(message) = Vakanuvis.log_via(@dmesg, :warn, message)
189
+
190
+ # Kapanış yolundaki son damıtım fırsatı (spawn yok — zombi doğum
191
+ # engeli); hata yalıtılmış: worker sökümü devam eder.
192
+ def worker_before_join
193
+ auto_digest_touched!(spawn: false)
194
+ rescue StandardError => e
195
+ Vakanuvis.log_via(@dmesg, :warn, "shutdown auto-digest failed (#{e.class}: #{e.message}) — worker teardown continues")
233
196
  end
234
197
 
235
- def run_worker
236
- loop do
237
- kind, payload = @queue.pop
238
- break if kind == STOP
198
+ def worker_drop_accounted(_item)
199
+ @monitor.synchronize { @dropped += 1 }
200
+ Vakanuvis.log_via(@dmesg, :warn, "event queue overflow — dropped oldest (total: #{@dropped})")
201
+ end
239
202
 
240
- handle_event(kind, payload)
241
- rescue StandardError => e
242
- # Last-ditch net: a raise escaping handle_event's own rescue
243
- # would kill the worker with queued events unconsumed — and
244
- # shutdown's alive?-check stays blind to that loss.
245
- Vakanuvis.log_via(@dmesg, :warn, "chronicler worker event dispatch failed (#{e.class}: #{e.message}) — worker continues")
246
- ensure
247
- @monitor.synchronize { @busy -= 1 }
248
- end
203
+ def worker_dispatch_failed(kind, _payload, error)
204
+ # A dispatch-lost event must leave a chronicle trace — the same
205
+ # ledger as overflow drops, so the session annal cannot look
206
+ # complete when it is not.
207
+ @monitor.synchronize { @dropped += 1 }
208
+ Vakanuvis.log_via(@dmesg, :warn, "chronicler worker event dispatch failed (#{error.class}: #{error.message}) — #{kind} event lost, worker continues")
249
209
  end
250
210
 
251
211
  # TranscriptIndexer disiplini: kronikçinin kendi hatası akışı
@@ -383,7 +343,7 @@ module Rubik
383
343
  @monitor.synchronize do
384
344
  if @dropped.positive?
385
345
  seq = @seq += 1
386
- overflow = [["dropped.#{seq}", "- [#{seq}] #{@dropped} event(s) dropped — queue overflow (event=dropped.#{seq})"]]
346
+ overflow = [["dropped.#{seq}", "- [#{seq}] #{@dropped} event(s) dropped — queue overflow or dispatch failure (event=dropped.#{seq})"]]
387
347
  @dropped = 0
388
348
  end
389
349
  end
@@ -129,18 +129,35 @@ module Rubik
129
129
  return [sub_path, nil]
130
130
  end
131
131
 
132
- return [filter, nil] unless filter =~ %r{\A([A-Za-z]:/|/)}
132
+ # Handle Windows drive letters portably across Linux, macOS and Windows
133
+ filter_drive = filter =~ %r{\A([A-Za-z]):(/.*)?\z} ? Regexp.last_match(1).upcase : nil
134
+ filter_path = filter_drive ? (Regexp.last_match(2) || "/") : filter
135
+ root_drive = norm_root =~ %r{\A([A-Za-z]):(/.*)?\z} ? Regexp.last_match(1).upcase : nil
136
+ root_path = root_drive ? (Regexp.last_match(2) || "/") : norm_root
137
+
138
+ outside = if (filter_drive && !root_drive) ||
139
+ (!filter_drive && root_drive && filter_path.start_with?("/")) ||
140
+ (filter_drive && root_drive && filter_drive != root_drive)
141
+ true
142
+ else
143
+ base_root = File.expand_path(root_path)
144
+ expanded = File.expand_path(filter_path, base_root)
145
+ rel_check = begin
146
+ Pathname.new(expanded).relative_path_from(Pathname.new(base_root)).to_s.tr("\\", "/")
147
+ rescue ArgumentError
148
+ nil
149
+ end
150
+ rel_check.nil? || rel_check == ".." || rel_check.start_with?("../")
151
+ end
133
152
 
134
- rel = begin
135
- Pathname.new(File.expand_path(filter)).relative_path_from(Pathname.new(File.expand_path(root_dir))).to_s.tr("\\", "/")
136
- rescue ArgumentError
137
- nil
138
- end
139
- outside = rel.nil? || rel == ".." || rel.start_with?("../")
140
153
  if outside
141
154
  return [nil, "Path '#{raw}' is outside the project workspace (#{root_dir}). " \
142
155
  "Use a path relative to the project root, e.g. 'lib'."]
143
156
  end
157
+
158
+ base_root = File.expand_path(root_path)
159
+ expanded = File.expand_path(filter_path, base_root)
160
+ rel = Pathname.new(expanded).relative_path_from(Pathname.new(base_root)).to_s.tr("\\", "/")
144
161
  return ["", nil] if rel == "."
145
162
 
146
163
  [rel, nil]
@@ -91,6 +91,7 @@ module Rubik
91
91
  "For surgical edits to existing files, use replace_file_content instead. " \
92
92
  "Use apply_buffer to persist the buffer to disk before running tests or tests will not see your changes.",
93
93
  risk: :write, archetypes: [:coder], write_grant: true, maestro_blocked: true, buffer_bound: true,
94
+ buffer_sync_writer: true,
94
95
  params_schema: {
95
96
  type: "object",
96
97
  properties: {
@@ -237,6 +238,7 @@ module Rubik
237
238
  description: "Replace an exact chunk of code within an existing file. Requires exact verbatim matching of target_content " \
238
239
  "(including whitespace and indentation). Optional start_line and end_line narrow the search range.",
239
240
  risk: :write, archetypes: [:coder], write_grant: true, maestro_blocked: true, buffer_bound: true,
241
+ buffer_sync_writer: true,
240
242
  params_schema: {
241
243
  type: "object",
242
244
  properties: {
@@ -18,15 +18,15 @@ module Rubik
18
18
 
19
19
  DECLARATION = Declaration.new(
20
20
  name: "update_goal_ledger", aliases: ["ledger"],
21
- description: "Update the structured goal ledger of the RUNNING !goal loop with a " \
22
- "JSON patch ({\"rev\": N, \"ops\": [{\"op\": ..., \"path\": ..., \"value\": ...}]}). " \
23
- "Read the current ledger via read_file(path: 'rubik://goal/ledger') and issue the " \
24
- "patch against the rev it reports. Rejections carry per-op fix hints; after the " \
25
- "retry budget the ledger stays unchanged — read it and continue. A task status of " \
26
- "`stale` means the harness re-checked that entry's verify predicate against the " \
27
- "filesystem and it FAILED (the world drifted): re-inspect reality, then update the " \
28
- "entry (including status) with a normal patch — a stale rev also means the ledger " \
29
- "moved under you.",
21
+ description: "Update the structured goal ledger of the RUNNING !goal loop with an RFC 6902 " \
22
+ "JSON patch ({\"rev\": N, \"ops\": [{\"op\": \"add\"|\"replace\"|\"remove\", \"path\": \"/tasks/0/status\", \"value\": ...}]}). " \
23
+ "Read current state via read_file(path: 'rubik://goal/ledger') (or 'rubik://goal/ledger.json') and issue " \
24
+ "the patch against the rev it reports. Items carry 0-based indices (/tasks/0); append via /tasks/-. " \
25
+ "Tasks and environment notes may carry declarative verify specs: {\"type\": \"file_exists\", \"path\": ...}, " \
26
+ "{\"type\": \"file_contains\", \"path\": ..., \"pattern\": ...}, or {\"type\": \"marker\", \"path\": ..., \"marker\": ...}. " \
27
+ "Rejections carry per-op fix hints; after the retry budget the ledger stays unchanged. A task status of " \
28
+ "`stale` means the harness re-checked that entry's verify predicate against the filesystem and it FAILED " \
29
+ "(the world drifted): re-inspect reality, then update the entry with a normal patch against the bumped rev.",
30
30
  risk: :write, archetypes: [], write_grant: false, root_only: true,
31
31
  maestro_blocked: false, # vakanüvis/pruner emsali: kök düzlem aracı
32
32
  params_schema: {
@@ -5,6 +5,7 @@ require_relative "../../coeffects"
5
5
  require_relative "../index_messages"
6
6
  require_relative "../output"
7
7
  require_relative "../native_search"
8
+ require_relative "../truncator"
8
9
  require_relative "../diagnostic_reporter"
9
10
 
10
11
  module Rubik
@@ -245,9 +246,7 @@ module Rubik
245
246
  end
246
247
 
247
248
  def sanitize_line_content(content)
248
- return content if content.length <= MAX_LINE_CHARS
249
-
250
- "#{content[0..MAX_LINE_CHARS]}... [line truncated, #{content.length} chars total]"
249
+ Rubik::Tools::Truncator.clip_line(content, MAX_LINE_CHARS)
251
250
  end
252
251
 
253
252
  def collect_disk_matches(matches, file_key, regex, max_results)
@@ -151,24 +151,14 @@ module Rubik
151
151
 
152
152
  return ToolOutput.error("Target and language_or_type must be provided.") if target.empty? || lang.empty?
153
153
 
154
- # 1. Automatic Probing if proposed_cmd is not specified or auto_probe is requested
154
+ # Phase 1: discovery (automatic probing when no command was provided)
155
155
  if !command_provided?(proposed_cmd) && auto_probe
156
- candidate = case target
157
- when "lsp" then Rubik::Runtime::Discovery.probe_lsp(lang, root_dir: @root_dir)
158
- when "test_runner" then Rubik::Runtime::Discovery.discover_test_runners(root_dir: @root_dir, lang: lang).first
159
- when "linter" then Rubik::Runtime::Discovery.discover_formatters(root_dir: @root_dir, lang: lang).first
160
- when "command" then Rubik::Runtime::Discovery.binary_available?(lang) ? lang : nil
161
- end
156
+ candidate = discover_target(target, lang)
162
157
 
163
158
  if candidate
164
159
  proposed_cmd = candidate
165
160
  else
166
- candidates = case target
167
- when "lsp" then Rubik::Runtime::Discovery.lsp_candidates(lang)
168
- when "test_runner" then Rubik::Runtime::Discovery.test_runner_candidates(lang, root_dir: @root_dir)
169
- when "linter" then Rubik::Runtime::Discovery::FORMATTER_CANDIDATES[lang] || []
170
- else []
171
- end
161
+ candidates = discovery_candidates(target, lang)
172
162
  cand_str = candidates.empty? ? "none" : candidates.join(", ")
173
163
  return ToolOutput.error("Auto-probe failed to discover any installed candidate for #{target} (#{lang}). " \
174
164
  "Candidates checked: [#{cand_str}]. Please provide a specific `proposed_command`.")
@@ -177,15 +167,66 @@ module Rubik
177
167
 
178
168
  return ToolOutput.error("No command provided or discovered for #{target} (#{lang}).") unless command_provided?(proposed_cmd)
179
169
 
180
- # 2. Pre-flight Verification in Isolated Sub-Context (ctx.extend())
170
+ # Phase 2: pre-flight verification in an isolated sub-context (ctx.extend())
181
171
  root_ctx = @runtime_manager&.context || Rubik::Runtime::Context.new
182
- sub_ctx = root_ctx.extend
172
+ verified, error_diagnostic = verify_in_sandbox(target, lang, proposed_cmd, root_ctx,
173
+ probe_args: args["probe_args"] || args[:probe_args])
174
+ return ToolOutput.error("Verification failed for #{target} (#{lang}):\n#{error_diagnostic&.format_for_llm}") unless verified
175
+
176
+ # Phase 3: promotion into a disposable transaction sub-context
177
+ result = promote(target, lang, proposed_cmd, root_ctx)
178
+ return result if result.is_a?(ToolOutput)
179
+
180
+ # Keep one lifetime inverse per repaired key, preserving the original
181
+ # baseline across repeated repairs without retaining every transaction.
182
+ promotion_ctx = result.promotion_ctx
183
+ scope_key = [root_ctx, result.service_key]
184
+ if @repair_scopes.key?(scope_key)
185
+ result.state.released = true
186
+ promotion_ctx.dispose
187
+ else
188
+ @repair_scopes[scope_key] = promotion_ctx
189
+ end
190
+
191
+ if @config.nil? && ["lsp", "test_runner", "linter"].include?(target)
192
+ return "⚠️ Promoted '#{display_command(proposed_cmd)}' for #{target} (#{lang}) — no config is attached, " \
193
+ "so the command is active for this session only and was not saved."
194
+ end
183
195
 
196
+ "✨ Successfully verified and promoted runtime service for #{target} (#{lang}): '#{display_command(proposed_cmd)}'. " \
197
+ "Service is now active in the live context."
198
+ end
199
+
200
+ private
201
+
202
+ # Phase 1: automatic probing of an installed candidate for the target.
203
+ def discover_target(target, lang)
204
+ case target
205
+ when "lsp" then Rubik::Runtime::Discovery.probe_lsp(lang, root_dir: @root_dir)
206
+ when "test_runner" then Rubik::Runtime::Discovery.discover_test_runners(root_dir: @root_dir, lang: lang).first
207
+ when "linter" then Rubik::Runtime::Discovery.discover_formatters(root_dir: @root_dir, lang: lang).first
208
+ when "command" then Rubik::Runtime::Discovery.binary_available?(lang) ? lang : nil
209
+ end
210
+ end
211
+
212
+ # Candidates surfaced in the error message when discovery finds nothing.
213
+ def discovery_candidates(target, lang)
214
+ case target
215
+ when "lsp" then Rubik::Runtime::Discovery.lsp_candidates(lang)
216
+ when "test_runner" then Rubik::Runtime::Discovery.test_runner_candidates(lang, root_dir: @root_dir)
217
+ when "linter" then Rubik::Runtime::Discovery::FORMATTER_CANDIDATES[lang] || []
218
+ else []
219
+ end
220
+ end
221
+
222
+ # Phase 2: pre-flight verification in an isolated sub-context. The probe
223
+ # sub-context is always disposed, even when verification raises.
224
+ def verify_in_sandbox(target, lang, proposed_cmd, root_ctx, probe_args: nil)
225
+ sub_ctx = root_ctx.extend
184
226
  verified = false
185
227
  error_diagnostic = nil
186
-
187
228
  begin
188
- verified, error_diagnostic = verify_binary(target, lang, proposed_cmd, sub_ctx, probe_args: args["probe_args"] || args[:probe_args])
229
+ verified, error_diagnostic = verify_binary(target, lang, proposed_cmd, sub_ctx, probe_args: probe_args)
189
230
  rescue StandardError => e
190
231
  error_diagnostic = Rubik::Runtime::DiagnosticEngine.diagnose(
191
232
  cmd: proposed_cmd,
@@ -195,13 +236,19 @@ module Rubik
195
236
  ensure
196
237
  sub_ctx.dispose
197
238
  end
239
+ [verified, error_diagnostic]
240
+ end
198
241
 
199
- return ToolOutput.error("Verification failed for #{target} (#{lang}):\n#{error_diagnostic&.format_for_llm}") unless verified
200
-
242
+ # Phase 3: apply the promoted command inside a disposable transaction
243
+ # sub-context. Returns a Promotion on success or a ToolOutput error with
244
+ # the rollback report; the `phase` marker distinguishes Promotion from
245
+ # Persistence failures. Rollbacks are named objects (see RollbackState)
246
+ # registered in LIFO order into the promotion sub-context.
247
+ def promote(target, lang, proposed_cmd, root_ctx)
201
248
  # Live changes belong to a disposable transaction. Successful project
202
249
  # persistence is an operator decision and outlives lifecycle cleanup.
203
250
  promotion_ctx = root_ctx.extend
204
- released = false
251
+ state = RollbackState.new
205
252
  @repair_scopes ||= {}
206
253
  cfg_key = { "lsp" => "lsp.servers", "test_runner" => "test.runners",
207
254
  "linter" => "linter.commands" }[target]
@@ -211,35 +258,13 @@ module Rubik
211
258
  previous_services = root_ctx.services
212
259
  phase = "Promotion"
213
260
  begin
214
- promotion_ctx.on_dispose do
215
- next if released
216
-
217
- @repair_scopes.delete([root_ctx, service_key]) if @repair_scopes[[root_ctx, service_key]].equal?(promotion_ctx)
218
- unless root_ctx.disposed?
219
- if previous_services.key?(service_key)
220
- if target == "lsp"
221
- restored = @lsp_manager&.clients&.[](lang)
222
- active = restored && (!restored.respond_to?(:alive?) || restored.alive?) &&
223
- (!restored.respond_to?(:running?) || restored.running?)
224
- if active
225
- root_ctx.provide(service_key, restored)
226
- else
227
- root_ctx.unprovide(service_key)
228
- end
229
- else
230
- root_ctx.provide(service_key, previous_services[service_key])
231
- end
232
- else
233
- root_ctx.unprovide(service_key)
234
- end
235
- end
236
- end
261
+ promotion_ctx.on_dispose(ServiceRollback.new(
262
+ root_ctx: root_ctx, promotion_ctx: promotion_ctx, service_key: service_key,
263
+ previous_services: previous_services, target: target, lang: lang,
264
+ lsp_manager: @lsp_manager, repair_scopes: @repair_scopes, state: state
265
+ ))
237
266
  if cfg_key && @config
238
- promotion_ctx.on_dispose do
239
- next if released
240
-
241
- prev_cmd.nil? ? @config.delete(cfg_key) : @config.set(cfg_key, prev_cmd)
242
- end
267
+ promotion_ctx.on_dispose(ConfigRollback.new(config: @config, cfg_key: cfg_key, prev_cmd: prev_cmd, state: state))
243
268
  @config.set(cfg_key, proposed_cmd)
244
269
  end
245
270
 
@@ -250,16 +275,10 @@ module Rubik
250
275
  had_client = !@lsp_manager.clients[lang].nil?
251
276
  # The manager owns its client table. Restore the old configured
252
277
  # client on rollback; probe clients never enter that table.
253
- promotion_ctx.on_dispose do
254
- next if released
255
-
256
- @lsp_manager.stop_client(lang)
257
- prev_cmd.nil? ? @config.delete(cfg_key) : @config.set(cfg_key, prev_cmd)
258
- if had_client && !root_ctx.disposed?
259
- restored = @lsp_manager.start_client(lang)
260
- raise "Previous LSP client could not be restarted: #{restored}" unless restored[:ok]
261
- end
262
- end
278
+ promotion_ctx.on_dispose(LspClientRollback.new(
279
+ lsp_manager: @lsp_manager, lang: lang, config: @config, cfg_key: cfg_key,
280
+ prev_cmd: prev_cmd, root_ctx: root_ctx, had_client: had_client, state: state
281
+ ))
263
282
  @lsp_manager.stop_client(lang)
264
283
  start_res = @lsp_manager.start_client(lang)
265
284
  raise "Failed to start LSP server: #{start_res}" unless start_res.is_a?(Hash) && start_res[:ok]
@@ -273,12 +292,11 @@ module Rubik
273
292
  field = target == "test_runner" ? :custom_test_cmd : :custom_format_cmd
274
293
  old_value = adapter.public_send(field)
275
294
  old_config = adapter.config
276
- promotion_ctx.on_dispose do
277
- next if released
278
-
279
- adapter.public_send("#{field}=", old_value)
280
- adapter.config = old_config
281
- end
295
+ promotion_ctx.on_dispose(AdapterFieldRollback.new(adapter: adapter, field: field,
296
+ old_value: old_value, old_config: old_config, state: state))
297
+ # Execution-time gate (TOCTOU closure): the probe ran once but the
298
+ # sink is unguarded; failure raises into the rescue below.
299
+ adapter.send(:validate_custom_command!, proposed_cmd)
282
300
  adapter.config ||= @config
283
301
  adapter.public_send("#{field}=", proposed_cmd)
284
302
  else
@@ -286,9 +304,9 @@ module Rubik
286
304
  options = target == "test_runner" ? { test_cmd: proposed_cmd } : { format_cmd: proposed_cmd }
287
305
  adapter = Rubik::Adapter::GenericAdapter.new(lang, **options, guard: @guard)
288
306
  adapter.config = @config
289
- promotion_ctx.on_dispose do
290
- @adapter_registry.unregister(lang) if !released && @adapter_registry.get(lang).equal?(adapter)
291
- end
307
+ promotion_ctx.on_dispose(AdapterUnregisterRollback.new(
308
+ adapter_registry: @adapter_registry, lang: lang, adapter: adapter, state: state
309
+ ))
292
310
  @adapter_registry.register(lang, adapter)
293
311
  end
294
312
  end
@@ -307,30 +325,11 @@ module Rubik
307
325
  detail = rollback_errors.empty? ? "previous session state restored" : "rollback incomplete: #{rollback_errors}"
308
326
  return ToolOutput.error("#{phase} failed for #{target} (#{lang}): #{e.message}; #{detail}")
309
327
  end
310
-
311
- # Keep one lifetime inverse per repaired key, preserving the original
312
- # baseline across repeated repairs without retaining every transaction.
313
- scope_key = [root_ctx, service_key]
314
- if @repair_scopes.key?(scope_key)
315
- released = true
316
- promotion_ctx.dispose
317
- else
318
- @repair_scopes[scope_key] = promotion_ctx
319
- end
320
-
321
- if @config.nil? && ["lsp", "test_runner", "linter"].include?(target)
322
- return "⚠️ Promoted '#{display_command(proposed_cmd)}' for #{target} (#{lang}) — no config is attached, " \
323
- "so the command is active for this session only and was not saved."
324
- end
325
-
326
- "✨ Successfully verified and promoted runtime service for #{target} (#{lang}): '#{display_command(proposed_cmd)}'. " \
327
- "Service is now active in the live context."
328
+ Promotion.new(promotion_ctx: promotion_ctx, service_key: service_key, state: state)
328
329
  end
329
330
 
330
- private
331
-
332
331
  def verify_binary(target, lang, proposed_cmd, sub_ctx, probe_args: nil)
333
- Rubik::Runtime::RepairProbe.new(root_dir: @root_dir).verify(target, lang, proposed_cmd, sub_ctx, probe_args: probe_args)
332
+ Rubik::Runtime::RepairProbe.new(root_dir: @root_dir, guard: @guard).verify(target, lang, proposed_cmd, sub_ctx, probe_args: probe_args)
334
333
  end
335
334
 
336
335
  def command_provided?(command)
@@ -373,3 +372,7 @@ module Rubik
373
372
  end
374
373
  end
375
374
  end
375
+
376
+ # Named rollback objects for RepairRuntimeTool are kept in a companion file
377
+ # (required after the class definition so it reopens it safely).
378
+ require_relative "../lifecycle_rollbacks"