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
@@ -56,12 +56,11 @@ module Rubik
56
56
  shell.guard.audit_log_path = val if shell.guard.respond_to?(:audit_log_path=)
57
57
  end
58
58
 
59
- cleanups << config.on_change("network.allow") do |_key, val, _old|
60
- config.set("sandbox.allow_network", val, persist: false) if config.fetch("sandbox.allow_network", nil) != val
61
- end
62
-
63
- cleanups << config.on_change("sandbox.allow_network") do |_key, val, _old|
64
- config.set("network.allow", val, persist: false) if config.fetch("network.allow", nil) != val
59
+ # network.allow is retired: the runner reads sandbox.allow_network
60
+ # only, so the mirror pushed writes into a key nothing reads back.
61
+ # The incantation stays accepted; it warns instead of mirroring.
62
+ cleanups << config.on_change("network.allow") do |_key, _val, _old|
63
+ warn "[ConfigWiring] [DEPRECATION] Config key 'network.allow' is deprecated and has no effect. Use 'sandbox.allow_network' instead."
65
64
  end
66
65
 
67
66
  cleanups
@@ -79,7 +78,17 @@ module Rubik
79
78
  new_roots = exp_roots - current_roots
80
79
  removed_roots = current_roots - exp_roots
81
80
 
82
- new_roots.each { |r| shell.buffer_manager&.add_root(r) }
81
+ new_roots.each do |r|
82
+ if shell.guard
83
+ begin
84
+ shell.guard.verify_root_safety!(r)
85
+ rescue Rubik::Security::BlockedWriteError => e
86
+ warn "[ConfigWiring] #{e.message}. Skipping additional root #{r}."
87
+ next
88
+ end
89
+ end
90
+ shell.buffer_manager&.add_root(r)
91
+ end
83
92
  removed_roots.each { |r| shell.buffer_manager&.remove_root(r) }
84
93
 
85
94
  if (new_roots.any? || removed_roots.any?) &&
@@ -97,6 +106,14 @@ module Rubik
97
106
  removed_dirs = current_dirs - exp_dirs
98
107
 
99
108
  new_dirs.each do |d|
109
+ if shell.guard
110
+ begin
111
+ shell.guard.verify_root_safety!(d)
112
+ rescue Rubik::Security::BlockedWriteError => e
113
+ warn "[ConfigWiring] #{e.message}. Skipping allowed directory #{d}."
114
+ next
115
+ end
116
+ end
100
117
  shell.buffer_manager.add_allowed_dir(d) if shell.buffer_manager.respond_to?(:add_allowed_dir)
101
118
  shell.sandbox_runner&.add_allowed_dir(d)
102
119
  end
@@ -231,7 +231,7 @@ module Rubik
231
231
  @active_loop = orchestrator
232
232
  res = orchestrator.run(text, conversation_history: @conversation_history)
233
233
 
234
- while !res[:ok] && res[:error]&.include?("Max steps budget exceeded") && @config.fetch("agent.ask_continue_on_limit", true)
234
+ while !res[:ok] && res[:reason] == :budget_exhausted && @config.fetch("agent.ask_continue_on_limit", true)
235
235
  @output.puts "\n⚠️ [Rubik::Agent] #{res[:error]}"
236
236
  ans = ask_yes_no(" [Rubik::Agent] +20 adım ile devam edilsin mi?", default: "n")
237
237
  break unless ["y", "yes", "evet"].include?(ans)
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "../events"
3
4
  require_relative "../log"
4
5
  require_relative "../orchestrator/subagent/notices"
5
6
  require_relative "../prompt/conversation_rows"
@@ -276,8 +277,8 @@ module Rubik
276
277
  tokens = Rubik::Orchestrator::Subagent::Notices::EVENTS.keys.map do |event|
277
278
  [event, @event_bus.subscribe(event) { |payload| handle_subagent_event(event, payload) }]
278
279
  end
279
- tokens << [:unit_state_changed, @event_bus.subscribe(:unit_state_changed) { |payload| handle_unit_event(payload) }]
280
- tokens << [:subagent_message_to_parent, @event_bus.subscribe(:subagent_message_to_parent) { |payload| handle_parent_message(payload) }]
280
+ tokens << [Rubik::Events::UNIT_STATE_CHANGED, @event_bus.subscribe(Rubik::Events::UNIT_STATE_CHANGED) { |payload| handle_unit_event(payload) }]
281
+ tokens << [Rubik::Events::SUBAGENT_MESSAGE_TO_PARENT, @event_bus.subscribe(Rubik::Events::SUBAGENT_MESSAGE_TO_PARENT) { |payload| handle_parent_message(payload) }]
281
282
  @subagent_event_tokens = tokens
282
283
  ctx.on_dispose do
283
284
  @subagent_event_tokens&.each { |(event, token)| @event_bus.unsubscribe(event, token) }
@@ -1,12 +1,16 @@
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 REPL
7
9
  module Pruner
8
10
  # Düzlem 1 çekirdeği (Vakanüvis::Harness yapısı): tek worker thread
9
- # + sınırlı FIFO. ANLIK GÖRÜNTÜ her zaman ÇAĞIRAN thread'de alınır
11
+ # + sınırlı FIFO (Concurrency::Worker iskeleti: atomik kabul,
12
+ # idempotent kapanış, busy sayımı ve son-çare ağı iskelettedir).
13
+ # ANLIK GÖRÜNTÜ her zaman ÇAĞIRAN thread'de alınır
10
14
  # (:turn_finished abonelik bloğu turn thread'inde koşar; araç/komut
11
15
  # çağrısı da turn thread'indedir) — worker shell durumuna ASLA
12
16
  # dokunmaz; o yalnız brif kurar, doğurur, hasat eder ve planı
@@ -14,10 +18,16 @@ module Rubik
14
18
  # — notice yok, wake yok, yalnız dmesg. Uygulama (pencere takası)
15
19
  # yalnız turn thread'inde, apply_staged_prune_plan! üzerinden.
16
20
  class Harness
17
- STOP = :__pruner_stop__
21
+ include Concurrency::Worker
22
+
23
+ # STOP işareti iskeletin tek ev sahibinde; sabit adı yaşar.
24
+ STOP = Concurrency::Worker::STOP
18
25
  MAX_QUEUE = 16
19
- TURN_EVENT = :turn_finished # TurnRecorder::TURN_EVENT_TARGET ile eş pinli
20
- COMPLETED_EVENT = :subagent_completed
26
+ # Olay adları tek evden okunur: Rubik::Events bağımlılıksız bir
27
+ # yapraktır (uris.rb öncülü) — izolasyon doktrini bozulmadan isimler
28
+ # yayıncı ve abonede aynı kaynaktan düşer.
29
+ TURN_EVENT = Rubik::Events::TURN_FINISHED
30
+ COMPLETED_EVENT = Rubik::Events::SUBAGENT_COMPLETED
21
31
  TYPE_NAME = "pruner"
22
32
  PRUNER_ROLE = "Context Pruner"
23
33
 
@@ -48,32 +58,6 @@ module Rubik
48
58
  self
49
59
  end
50
60
 
51
- def stopped? = @monitor.synchronize { @stopped }
52
-
53
- # Dispose sözleşmesi (vakanüvis): FIFO drain olur (STOP dahil önceki
54
- # olaylar işlenir), thread 2 saniyede durmazsa kill + dürüst dmesg.
55
- def shutdown
56
- @monitor.synchronize { @stopped = true }
57
- @monitor.synchronize { @busy += 1 }
58
- @queue.push(STOP)
59
- @worker&.join(2)
60
- if @worker&.alive?
61
- Pruner.log_via(@dmesg, :warn, "worker did not stop in 2s — killing with #{queue_size} event(s) unprocessed")
62
- @worker.kill
63
- end
64
- @worker = nil
65
- end
66
-
67
- def wait_idle(timeout: 2.0)
68
- deadline = Time.now + timeout
69
- sleep 0.01 while busy? && Time.now < deadline
70
- !busy?
71
- end
72
-
73
- def busy? = @monitor.synchronize { @busy.positive? }
74
-
75
- def queue_size = @queue.size
76
-
77
61
  # ---- talep düzlemi (prune_context aracı / !prune komutu) ----------
78
62
 
79
63
  # Zorunlu budama isteği: LLM asla bekletilmez — deterministik makbuz
@@ -106,6 +90,19 @@ module Rubik
106
90
  bits: @gate.status_bits)
107
91
  end
108
92
 
93
+ # ---- olay giriş kapısı ----------------------------------------------
94
+
95
+ # Atomik kabul (stopped-kontrol + push tek kritik bölümde) iskelette:
96
+ # kapanış yarışındaki olay ya STOP'tan önce düşer ve işlenir ya da
97
+ # reddedilir — işleyeneksiz bir olay busy sayımını sızdıramaz.
98
+ def enqueue_event(kind, payload)
99
+ unless payload.is_a?(Hash)
100
+ Pruner.log_via(@dmesg, :warn, "discarded non-hash #{kind} event (#{payload.class})")
101
+ return false
102
+ end
103
+ super
104
+ end
105
+
109
106
  private
110
107
 
111
108
  def subscribe_events
@@ -123,6 +120,9 @@ module Rubik
123
120
  envelope, = @gate.stage_job(@shell.conversation_history, reason: "turn", forced: false)
124
121
  @gate.drop_job(envelope, why: "harness stopped") if envelope && !enqueue_job(envelope)
125
122
  end
123
+ # A completion refused at teardown drops without gate reconcile —
124
+ # terminal by design: the session is ending, nothing reads the
125
+ # gate afterwards.
126
126
  @event_bus.subscribe(COMPLETED_EVENT, context: @context) { |p| enqueue_event(:completed, p) }
127
127
  end
128
128
 
@@ -130,50 +130,35 @@ module Rubik
130
130
  enqueue_event(:job, { envelope: envelope })
131
131
  end
132
132
 
133
- def enqueue_event(kind, payload)
134
- return false if stopped?
133
+ # ---- Concurrency::Worker iskelet kancaları --------------------------
135
134
 
136
- unless payload.is_a?(Hash)
137
- Pruner.log_via(@dmesg, :warn, "discarded non-hash #{kind} event (#{payload.class})")
138
- return false
139
- end
135
+ def worker_max_queue = MAX_QUEUE
140
136
 
141
- drop_oldest! if @queue.size >= MAX_QUEUE
142
- @monitor.synchronize { @busy += 1 }
143
- @queue.push([kind, payload])
144
- true
145
- end
137
+ def worker_warn(message) = Pruner.log_via(@dmesg, :warn, message)
146
138
 
147
- # Taşma düşürmesi asla STOP'u yutamaz (vakanüvis kuralı); düşen
148
- # işin gate'teki izi uzlaştırılır — :job yer tutucusu temizlenir,
149
- # :completed sicil girdisi silinir (kapı asla "uçuşta" takılı
150
- # kalamaz) ve taşan tamamlanmanın id'si loglanır.
151
- def drop_oldest!
152
- item = @queue.pop(true)
153
- if item == STOP
154
- @queue.push(STOP)
155
- else
156
- @monitor.synchronize { @busy -= 1 }
157
- if item[0] == :job
158
- @gate.drop_job(item[1][:envelope], why: "queue overflow")
159
- elsif item[0] == :completed
160
- @gate.discard_completion(item[1])
161
- end
162
- Pruner.log_via(@dmesg, :warn, "event queue overflow — dropped oldest #{item[0]} event")
139
+ # Taşma düşürmesi gate'in izini uzlaştırır — :job yer tutucusu
140
+ # temizlenir, :completed sicil girdisi silinir (kapı asla "uçuşta"
141
+ # takılı kalamaz) ve taşan tamamlanmanın id'si loglanır.
142
+ def worker_drop_accounted(item)
143
+ if item[0] == :job
144
+ @gate.drop_job(item[1][:envelope], why: "queue overflow")
145
+ elsif item[0] == :completed
146
+ @gate.discard_completion(item[1])
163
147
  end
164
- rescue ThreadError
165
- nil
148
+ Pruner.log_via(@dmesg, :warn, "event queue overflow — dropped oldest #{item[0]} event")
166
149
  end
167
150
 
168
- def run_worker
169
- loop do
170
- kind, payload = @queue.pop
171
- break if kind == STOP
172
-
173
- handle_event(kind, payload)
174
- ensure
175
- @monitor.synchronize { @busy -= 1 }
151
+ def worker_dispatch_failed(kind, payload, error)
152
+ # A lost dispatch must reconcile the gate like an overflow drop —
153
+ # an unreconciled :job placeholder or :completed entry would wedge
154
+ # every later prune behind "already in flight".
155
+ case kind
156
+ when :job
157
+ @gate.drop_job(payload[:envelope], why: "dispatch failed") if payload.is_a?(Hash)
158
+ when :completed
159
+ @gate.discard_completion(payload) if payload.is_a?(Hash)
176
160
  end
161
+ Pruner.log_via(@dmesg, :warn, "pruner worker event dispatch failed (#{error.class}: #{error.message}) — worker continues")
177
162
  end
178
163
 
179
164
  # Pruner'in kendi hatası REPL akışını asla bozmaz — uyarı düşer,
@@ -230,7 +230,9 @@ module Rubik
230
230
  # satırı doğması aynı enjeksiyon sınıfıdır — etiketler özet
231
231
  # içinde asla birebir yaşayamaz.
232
232
  clean = clean.gsub("<user_task>", "&lt;user_task&gt;").gsub("</user_task>", "&lt;/user_task&gt;")
233
- clean = clean.gsub("<goal_ledger ", "&lt;goal_ledger ").gsub("</goal_ledger>", "&lt;/goal_ledger>")
233
+ # Etiket adları gramer tek evinden (ContextCompactor) okunur.
234
+ gtag = Prompt::ContextCompactor::GOAL_LEDGER_TAG
235
+ clean = clean.gsub("<#{gtag} ", "&lt;#{gtag} ").gsub("</#{gtag}>", "&lt;/#{gtag}>")
234
236
  clean_op["text"] = clean
235
237
  end
236
238
  normalized << clean_op
@@ -1,5 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "../../storage/layout"
4
+
3
5
  module Rubik
4
6
  module REPL
5
7
  module Pruner
@@ -66,15 +68,8 @@ module Rubik
66
68
  # Noktalı anahtar okuması iki config şeklinde de aynı çalışsın
67
69
  # (maestro_gate.rb:38-40 düzeni): Rubik::Config#fetch noktalı yolu
68
70
  # böler, düz Hash hepsini tek anahtar sayar → dig'e düş.
69
- def config_get(config, key, default)
70
- return default if config.nil?
71
-
72
- val = if config.is_a?(Hash)
73
- config.dig(*key.to_s.split("."))
74
- elsif config.respond_to?(:fetch)
75
- config.fetch(key, nil)
76
- end
77
- val.nil? ? default : val
71
+ def config_get(config, key, default = nil)
72
+ Rubik::Storage::Layout.config_get(config, key, default)
78
73
  end
79
74
  end
80
75
  end
@@ -111,7 +111,7 @@ module Rubik
111
111
  # path in the same session without restarts.
112
112
  DEFINITION.new(
113
113
  name: :guard,
114
- builder: ->(s) { Rubik::Security::Guard.for_config(s[:config]) },
114
+ builder: ->(s) { Rubik::Security::Guard.for_config(s[:config], root_dir: s.root_dir) },
115
115
  provide: Rubik::Coeffects::GUARD
116
116
  ),
117
117
  DEFINITION.new(
@@ -0,0 +1,3 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../runtime/synthesized_command_context"
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "../events"
3
4
  require_relative "../prompt/context_compactor"
4
5
  require_relative "../coeffects"
5
6
 
@@ -13,10 +14,10 @@ module Rubik
13
14
  module TurnRecorder
14
15
  MAX_CONVERSATION_ENTRIES = Rubik::Prompt::ContextCompactor::DEFAULT_MAX_CONVERSATION_ENTRIES
15
16
 
16
- # Vakanüvis kök-turn olay adı — harness'in TURN_EVENT sabitiyle eş
17
- # pinlenir (testler iki taraftan kilitler; isim çelişkisi koşuldan
18
- # önce patlar).
19
- TURN_EVENT_TARGET = :turn_finished
17
+ # Vakanüvis kök-turn olay adı — tek ev Rubik::Events yaprağı; harness
18
+ # sabitleri aynı yapraktan okur, isim çelişkisi tasarım aşamasında
19
+ # imkânsızlaşır.
20
+ TURN_EVENT_TARGET = Rubik::Events::TURN_FINISHED
20
21
 
21
22
  # Plan 61 D-7: sticky routing. Once a conversation has started,
22
23
  # free-text turns keep the established provider/model instead of
data/lib/rubik/repl.rb CHANGED
@@ -6,6 +6,7 @@ require_relative "repl/step_formatter"
6
6
  require_relative "repl/commands"
7
7
  require_relative "repl/terminal_guard"
8
8
  require_relative "repl/pruner"
9
+ require_relative "repl/synthesized_command_context"
9
10
  require_relative "repl/shell"
10
11
 
11
12
  module Rubik
@@ -7,6 +7,11 @@ module Rubik
7
7
  module Runtime
8
8
  class CoeffectMissingError < StandardError; end
9
9
 
10
+ # Raised when a sealed context denies a coeffect lookup by policy.
11
+ # Subclasses CoeffectMissingError so existing rescue clauses keep
12
+ # matching.
13
+ class CoeffectBlockedError < CoeffectMissingError; end
14
+
10
15
  # Raised when a disposed context is asked to create new scope. Unlike a
11
16
  # late inverse (which can run now), there is no meaningful fallback for
12
17
  # extend, so it fails fast (AGENTS.md Fail Fast template).
@@ -74,6 +79,8 @@ module Rubik
74
79
  def provide(name, service)
75
80
  key = name.to_s.downcase
76
81
  @monitor.synchronize do
82
+ raise ContextDisposedError, "Cannot provide '#{name}' on a disposed context." if @disposed
83
+
77
84
  already_provided = @services.key?(key)
78
85
  @services[key] = service
79
86
  return if already_provided
@@ -219,6 +226,10 @@ module Rubik
219
226
  protected :prune_child
220
227
 
221
228
  def dispose
229
+ return if disposed?
230
+
231
+ # Resolve dmesg outside monitor to preserve parent→child lock order (F3).
232
+ dmesg = resolve_dmesg
222
233
  parent = nil
223
234
  deferred_interrupt = nil
224
235
  @monitor.synchronize do
@@ -230,7 +241,6 @@ module Rubik
230
241
  # (record_deferred_signal) survive into the final
231
242
  # last_dispose_errors instead of being wiped by this reset.
232
243
  @last_dispose_errors = []
233
- dmesg = resolve_dmesg
234
244
  # Counted before the cascade: disposing children prune their
235
245
  # inverses from our accumulator (pre-cascade size is what the
236
246
  # "beginning" log reports).
@@ -175,6 +175,8 @@ module Rubik
175
175
  "node" => "npm test"
176
176
  }.freeze
177
177
 
178
+ SHELL_METACHARACTERS = /[;&|<>`$(){}\[\]\\\n\r]/
179
+
178
180
  class << self
179
181
  def lsp_candidates(lang)
180
182
  LSP_CANDIDATES[lang.to_s.downcase] || []
@@ -322,6 +324,59 @@ module Rubik
322
324
  ext_to_lang[best_ext] || "ruby"
323
325
  end
324
326
 
327
+ # Return all recognized candidate command prefixes for a workspace
328
+ def all_candidate_commands(root_dir: Dir.pwd, config: nil)
329
+ effective_root = root_dir || Dir.pwd
330
+ candidates = []
331
+
332
+ # 1. Detected primary language test runners
333
+ primary_lang = detect_primary_language(effective_root)
334
+ if primary_lang
335
+ candidates.concat(test_runner_candidates(primary_lang, root_dir: effective_root, config: config))
336
+ candidates.concat(FORMATTER_CANDIDATES[primary_lang] || [])
337
+ end
338
+
339
+ # 2. Check all marker rules whose files exist in effective_root
340
+ TEST_RUNNER_MARKERS.each do |lang, rules|
341
+ rules.each do |rule|
342
+ marker_path = File.join(effective_root, rule[:marker])
343
+ if File.exist?(marker_path)
344
+ candidates.concat(rule[:candidates])
345
+ candidates.concat(FORMATTER_CANDIDATES[lang] || [])
346
+ end
347
+ end
348
+ end
349
+
350
+ # 3. Add default runners as fallback
351
+ DEFAULT_TEST_RUNNERS.each_value { |runner| candidates << runner }
352
+
353
+ # 4. Include explicit config overrides if provided
354
+ if config
355
+ ["ruby", "python", "rust", "go", "zig", "c", "typescript", "javascript", "vue", "node"].each do |l|
356
+ cfg_cmd = resolve_config_test_cmd(config, l)
357
+ candidates << cfg_cmd if cfg_cmd && !cfg_cmd.empty?
358
+ end
359
+ end
360
+
361
+ candidates.compact.map(&:strip).reject(&:empty?).uniq
362
+ end
363
+
364
+ # True if cmd_str matches a recognized Discovery candidate for the given root_dir
365
+ def recognized_candidate?(cmd_str, root_dir: Dir.pwd, config: nil)
366
+ return false if cmd_str.nil? || cmd_str.to_s.strip.empty?
367
+ return false if cmd_str.to_s.match?(SHELL_METACHARACTERS)
368
+
369
+ clean_cmd = cmd_str.to_s.strip
370
+ candidates = all_candidate_commands(root_dir: root_dir, config: config)
371
+
372
+ # Check exact match or prefix match on whitespace/argument boundaries
373
+ candidates.any? do |candidate|
374
+ clean_cmd == candidate ||
375
+ clean_cmd.start_with?("#{candidate} ") ||
376
+ clean_cmd.start_with?("#{candidate}\t")
377
+ end
378
+ end
379
+
325
380
  private
326
381
 
327
382
  def resolve_config_test_cmd(config, lang_key)
@@ -90,12 +90,13 @@ module Rubik
90
90
  true
91
91
  rescue StandardError => e
92
92
  # Atomic Rollback on Error: unwind partial inverses immediately
93
- @sub_context&.dispose
94
- @sub_context = nil
95
- @instance = nil
96
- @state = :failed
97
- @last_error = e
93
+ rollback_activation!(e)
98
94
  false
95
+ rescue Exception => e # rubocop:disable Lint/RescueException
96
+ # Failure Reversibility on fatal exceptions/signals (Interrupt, SystemExit):
97
+ # execute partial inverses immediately to restore the environment, then re-raise (AGENTS.md §1.A).
98
+ rollback_activation!(e)
99
+ raise
99
100
  end
100
101
  end
101
102
 
@@ -130,6 +131,17 @@ module Rubik
130
131
  def build_instance(_sub_context, _config)
131
132
  nil
132
133
  end
134
+
135
+ private
136
+
137
+ def rollback_activation!(error)
138
+ ctx = @sub_context
139
+ @sub_context = nil
140
+ @instance = nil
141
+ @state = :failed
142
+ @last_error = error
143
+ ctx&.dispose
144
+ end
133
145
  end
134
146
 
135
147
  # Backwards-compatibility alias (AGENTS.md terminology). Kept for external
@@ -101,7 +101,11 @@ module Rubik
101
101
  # object is re-provided (identity change), so its new instance is injected.
102
102
  # Both transitions run reconcile_all(changed_service:) OUTSIDE the monitor.
103
103
  def provide(service_name, service)
104
- @monitor.synchronize { @context.provide(service_name, service) }
104
+ @monitor.synchronize do
105
+ raise ContextDisposedError, "Cannot provide service on a disposed Manager" if @disposed
106
+
107
+ @context.provide(service_name, service)
108
+ end
105
109
  # reconcile_all runs OUTSIDE this lock so a failing fiber's backoff sleep
106
110
  # never serializes other threads (Finding 3).
107
111
  reconcile_all(changed_service: service_name)
@@ -198,22 +202,25 @@ module Rubik
198
202
  end
199
203
 
200
204
  def dispose!
205
+ fibers_to_dispose = nil
201
206
  @monitor.synchronize do
202
207
  return if @disposed
203
208
 
204
209
  @disposed = true
205
- begin
206
- @fibers.values.reverse_each do |fiber|
207
- fiber.dispose!
208
- rescue StandardError => e
209
- Rubik::Log.warn(:runtime, "fiber '#{fiber.name}' dispose failed: #{e.class}: #{e.message}")
210
- end
211
- ensure
212
- @fibers.clear
213
- @retry_gate.clear_all # fresh-eye R2: no bookkeeping outlives the manager
214
- @context.dispose
215
- end
210
+ fibers_to_dispose = @fibers.values.reverse
211
+ @fibers.clear
212
+ @retry_gate.clear_all # fresh-eye R2: no bookkeeping outlives the manager
213
+ end
214
+
215
+ # Execute fiber teardown and context disposal OUTSIDE the monitor lock
216
+ # so arbitrary user teardown inverses never serialize manager operations (Finding F4).
217
+ fibers_to_dispose.each do |fiber|
218
+ fiber.dispose!
219
+ rescue StandardError => e
220
+ Rubik::Log.warn(:runtime, "fiber '#{fiber.name}' dispose failed: #{e.class}: #{e.message}")
216
221
  end
222
+
223
+ @context.dispose
217
224
  end
218
225
 
219
226
  private