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
@@ -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)
@@ -96,7 +96,7 @@ module Rubik
96
96
  # Push non-empty command to history
97
97
  @reline::HISTORY.push(line) if !prompt_grace_interactive? && !line.strip.empty? && line != begin
98
98
  @reline::HISTORY.to_a.last
99
- rescue
99
+ rescue StandardError
100
100
  nil
101
101
  end
102
102
 
@@ -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"
@@ -142,6 +143,9 @@ module Rubik
142
143
  # never forces async warm in tests.
143
144
  warm_async = Platform.async_knob(@config, "ast.async_warm")
144
145
  maybe_warn_huge_root!
146
+ # Boot accumulated config problems (unknown keys, corrupt YAML, legacy
147
+ # env vars) surface here — same notices seam, still before the banner.
148
+ maybe_emit_config_warnings!
145
149
  # A strong huge-root signal skips the boot warm walk: the index
146
150
  # stays empty and tools answer the honest not-ready message until
147
151
  # an explicit '!context scan' opts in. Warning only — never a block.
@@ -220,6 +224,31 @@ module Rubik
220
224
  !@config.fetch("context.boot_scan_on_huge_root", false)
221
225
  end
222
226
 
227
+ # Boot-time config observability (issue #399): Config#warnings
228
+ # accumulates unknown-key, corrupt-YAML, ~/.rubik and env-deprecation
229
+ # problems during load with no reader; this surfaces them through the
230
+ # notices seam right after the huge-root check, before the banner.
231
+ # Once per REPL process boot — warnings appended later in the session
232
+ # (runtime set()) stay in the array for !config/tests without printing.
233
+ # Rubik::Log.warn mirrors each notice so headless/scripted boots see
234
+ # them on stderr too.
235
+ def maybe_emit_config_warnings!
236
+ warnings = @config&.warnings
237
+ return if warnings.nil? || warnings.empty?
238
+ return if @config_warnings_shown
239
+
240
+ @config_warnings_shown = true
241
+ warnings.each do |w|
242
+ line = "⚠ Config: #{w}"
243
+ Rubik::Log.warn(:config, line)
244
+ if @terminal_guard
245
+ @terminal_guard.print_safe_notice(line)
246
+ else
247
+ @output&.puts line
248
+ end
249
+ end
250
+ end
251
+
223
252
  # Async MCP boot progress notices (mcp-async-boot D8): subscribe BEFORE
224
253
  # the boot triggers so no event is missed, with the unsubscribe inverse
225
254
  # registered in the same breath (wire_subagent_events! pattern). Async
@@ -276,8 +305,8 @@ module Rubik
276
305
  tokens = Rubik::Orchestrator::Subagent::Notices::EVENTS.keys.map do |event|
277
306
  [event, @event_bus.subscribe(event) { |payload| handle_subagent_event(event, payload) }]
278
307
  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) }]
308
+ tokens << [Rubik::Events::UNIT_STATE_CHANGED, @event_bus.subscribe(Rubik::Events::UNIT_STATE_CHANGED) { |payload| handle_unit_event(payload) }]
309
+ tokens << [Rubik::Events::SUBAGENT_MESSAGE_TO_PARENT, @event_bus.subscribe(Rubik::Events::SUBAGENT_MESSAGE_TO_PARENT) { |payload| handle_parent_message(payload) }]
281
310
  @subagent_event_tokens = tokens
282
311
  ctx.on_dispose do
283
312
  @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
@@ -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).
@@ -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)
@@ -0,0 +1,116 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "time"
5
+ # save_manifest atomik yazımı Platform.atomic_write kullanır; dosyanın tek başına
6
+ # require edilmesi durumunda da çözümlenebilsin diye açık yüklenir.
7
+ require_relative "../platform"
8
+ require_relative "../plugin/package_inventory"
9
+
10
+ module Rubik
11
+ module Runtime
12
+ # Single home of the manifest primitives shared by Plugin::Storage and
13
+ # Runtime::OverlayStorage (issue #426): path resolution, load/save (atomic
14
+ # write via Platform.atomic_write), per-basename hash recording, hash
15
+ # verification (ONE comparison policy — constant-time, via
16
+ # Plugin::PackageInventory.secure_compare), the RUBIK_TRUST_OVERLAYS
17
+ # trust-mode seam, and the fail-closed corrupt-manifest contract.
18
+ #
19
+ # A store is directory-agnostic: callers resolve which directory a scope
20
+ # maps to. An optional `validate_path` callable receives (path, dir)
21
+ # before any manifest I/O — OverlayStorage wires its overlay-dir and
22
+ # containment checks here; Plugin::Storage passes nil (its directories
23
+ # are self-created under root/home).
24
+ class ManifestStore
25
+ MANIFEST_NAME = ".manifest.json"
26
+
27
+ def initialize(validate_path: nil)
28
+ @validate_path = validate_path
29
+ end
30
+
31
+ def manifest_path(dir)
32
+ path = File.join(dir, MANIFEST_NAME)
33
+ @validate_path&.call(path, dir)
34
+ path
35
+ end
36
+
37
+ def load_manifest(dir)
38
+ path = manifest_path(dir)
39
+ return {} unless File.exist?(path)
40
+
41
+ JSON.parse(File.read(path))
42
+ rescue JSON::ParserError, ArgumentError
43
+ {}
44
+ end
45
+
46
+ # Atomik yazım (tmp + rename): kilitsiz okuyucuların yarım manifest
47
+ # görmesini engeller (Platform.atomic_write).
48
+ def save_manifest(dir, manifest)
49
+ Platform.atomic_write(manifest_path(dir), JSON.pretty_generate(manifest))
50
+ end
51
+
52
+ # Per-basename hash record: load → merge → save. The caller owns hash
53
+ # computation (file vs normalized content) and pre-write guards; the
54
+ # store owns the entry shape and the manifest mutation.
55
+ def record_hash(dir, filename, hash, scope:)
56
+ manifest = load_manifest(dir)
57
+ manifest[filename] = {
58
+ "sha256" => hash,
59
+ "scope" => scope.to_s,
60
+ "created_at" => Time.now.iso8601
61
+ }
62
+ save_manifest(dir, manifest)
63
+ end
64
+
65
+ # Symmetric retraction: remove a basename and persist. Returns whether
66
+ # the key existed (mirrors Hash#delete's semantics).
67
+ def remove_entry(dir, filename)
68
+ manifest = load_manifest(dir)
69
+ existed = manifest.delete(filename)
70
+ save_manifest(dir, manifest) if existed
71
+ !existed.nil?
72
+ end
73
+
74
+ # The ONE hash-comparison policy. Returns :verified, :drift (recorded
75
+ # hash mismatch) or :unknown (basename not consented). Callers own the
76
+ # user-facing warn wording for :drift/:unknown — both map to :rejected.
77
+ def verify_entry(manifest, basename, current_hash)
78
+ return :unknown unless manifest.key?(basename)
79
+ return :verified if Rubik::Plugin::PackageInventory.secure_compare(current_hash, manifest[basename]["sha256"])
80
+
81
+ :drift
82
+ end
83
+
84
+ # Single trust-mode seam (issue #426): the blanket operator override
85
+ # read exactly once, here. Both storage planes (plugin and overlay)
86
+ # delegate to this predicate.
87
+ def trust_mode?
88
+ ENV["RUBIK_TRUST_OVERLAYS"] == "1"
89
+ end
90
+
91
+ # Three-state manifest probe: :missing / :valid / :corrupt. load_manifest
92
+ # deliberately keeps its {} behavior; the record/delete paths refuse
93
+ # through refuse_corrupt_manifest! instead of silently healing.
94
+ def manifest_state(dir)
95
+ path = manifest_path(dir)
96
+ return :missing unless File.exist?(path)
97
+
98
+ parsed = JSON.parse(File.read(path))
99
+ parsed.is_a?(Hash) ? :valid : :corrupt
100
+ rescue JSON::ParserError
101
+ :corrupt
102
+ end
103
+
104
+ # Single home of the fail-closed corrupt-manifest contract (issue #407):
105
+ # record and delete refuse through this one raise instead of healing a
106
+ # corrupt manifest (which would evict the other consented entries).
107
+ # `verb` reproduces the per-site message ("cannot record '...'" vs
108
+ # "cannot delete '...'"); the rest of the template is verbatim shared.
109
+ def refuse_corrupt_manifest!(dir, verb, filename)
110
+ return unless manifest_state(dir) == :corrupt
111
+
112
+ raise "cannot #{verb} '#{filename}': .manifest.json in #{dir} is corrupt; delete it and re-record overlays"
113
+ end
114
+ end
115
+ end
116
+ end