rubik 0.7.1 → 0.8.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 (78) hide show
  1. checksums.yaml +4 -4
  2. data/ATTRIBUTION.md +1 -1
  3. data/CHANGELOG.md +205 -1
  4. data/lib/rubik/ast/typescript_extractor.rb +2 -2
  5. data/lib/rubik/config/deep_ops.rb +14 -0
  6. data/lib/rubik/config/defaults.rb +5 -4
  7. data/lib/rubik/config/env_loader.rb +88 -0
  8. data/lib/rubik/config/model_catalog.rb +13 -0
  9. data/lib/rubik/config/pruner.rb +34 -0
  10. data/lib/rubik/config/schema.rb +163 -0
  11. data/lib/rubik/config/scoped.rb +108 -0
  12. data/lib/rubik/config/store.rb +19 -8
  13. data/lib/rubik/config.rb +129 -53
  14. data/lib/rubik/diagnostics/parser.rb +2 -2
  15. data/lib/rubik/kernel/dispatcher.rb +19 -23
  16. data/lib/rubik/kernel/init.rb +22 -18
  17. data/lib/rubik/orchestrator/goal_ledger/ledger.rb +3 -9
  18. data/lib/rubik/orchestrator/goal_ledger/observation_projection.rb +3 -9
  19. data/lib/rubik/orchestrator/step_executor.rb +12 -59
  20. data/lib/rubik/orchestrator/subagent/deferred_spec.rb +51 -2
  21. data/lib/rubik/orchestrator/subagent/dependency.rb +20 -20
  22. data/lib/rubik/orchestrator/subagent/execution_reads.rb +1 -1
  23. data/lib/rubik/orchestrator/subagent/journal.rb +3 -9
  24. data/lib/rubik/orchestrator/subagent/lifecycle.rb +10 -1
  25. data/lib/rubik/orchestrator/subagent/paging.rb +49 -0
  26. data/lib/rubik/orchestrator/subagent/reaper.rb +1 -3
  27. data/lib/rubik/orchestrator/subagent/redeploy_transaction.rb +99 -0
  28. data/lib/rubik/orchestrator/subagent/result_archive.rb +12 -22
  29. data/lib/rubik/orchestrator/subagent/reuse.rb +37 -31
  30. data/lib/rubik/orchestrator/subagent/scoped_registry.rb +14 -23
  31. data/lib/rubik/orchestrator/subagent/spawn_transaction.rb +13 -3
  32. data/lib/rubik/orchestrator/subagent/supervisor.rb +6 -2
  33. data/lib/rubik/orchestrator/subagent/task_ownership.rb +2 -2
  34. data/lib/rubik/orchestrator/subagent/tool_dispatch.rb +12 -49
  35. data/lib/rubik/orchestrator/subagent/transcript_reader.rb +14 -13
  36. data/lib/rubik/orchestrator/turn_executor.rb +9 -4
  37. data/lib/rubik/repl/commands/subagents.rb +3 -2
  38. data/lib/rubik/repl/commands/workspace.rb +14 -8
  39. data/lib/rubik/repl/lifecycle.rb +11 -0
  40. data/lib/rubik/repl/pruner/service.rb +4 -9
  41. data/lib/rubik/repl/service_catalog.rb +2 -1
  42. data/lib/rubik/runtime/context.rb +6 -1
  43. data/lib/rubik/runtime/fiber.rb +17 -5
  44. data/lib/rubik/runtime/manager.rb +19 -12
  45. data/lib/rubik/sandbox/runner.rb +28 -13
  46. data/lib/rubik/storage/layout.rb +14 -3
  47. data/lib/rubik/storage/render.rb +1 -1
  48. data/lib/rubik/storage/vakanuvis/distill_gate.rb +3 -3
  49. data/lib/rubik/storage/vakanuvis/harness.rb +4 -65
  50. data/lib/rubik/storage/vakanuvis/orientation.rb +1 -2
  51. data/lib/rubik/storage/vakanuvis/recall.rb +84 -0
  52. data/lib/rubik/storage/vakanuvis.rb +1 -0
  53. data/lib/rubik/tools/base.rb +65 -0
  54. data/lib/rubik/tools/builtins/define_subagent.rb +6 -0
  55. data/lib/rubik/tools/builtins/dmesg.rb +5 -5
  56. data/lib/rubik/tools/builtins/exec.rb +1 -2
  57. data/lib/rubik/tools/builtins/files.rb +19 -25
  58. data/lib/rubik/tools/builtins/goal_ledger.rb +2 -2
  59. data/lib/rubik/tools/builtins/grep.rb +8 -8
  60. data/lib/rubik/tools/builtins/interactive.rb +7 -3
  61. data/lib/rubik/tools/builtins/lifecycle.rb +2 -1
  62. data/lib/rubik/tools/builtins/lsp.rb +2 -2
  63. data/lib/rubik/tools/builtins/pruner.rb +2 -2
  64. data/lib/rubik/tools/builtins/runtime.rb +1 -1
  65. data/lib/rubik/tools/builtins/send_message.rb +20 -3
  66. data/lib/rubik/tools/builtins/skill.rb +1 -1
  67. data/lib/rubik/tools/builtins/storage.rb +1 -1
  68. data/lib/rubik/tools/builtins/subagent.rb +14 -1
  69. data/lib/rubik/tools/builtins/subagent_lifecycle.rb +5 -3
  70. data/lib/rubik/tools/builtins/symbols.rb +4 -4
  71. data/lib/rubik/tools/builtins/task.rb +1 -1
  72. data/lib/rubik/tools/builtins/vakanuvis.rb +2 -2
  73. data/lib/rubik/tools/catalog.rb +19 -0
  74. data/lib/rubik/tools/declaration.rb +15 -2
  75. data/lib/rubik/tools/result_normalizer.rb +115 -0
  76. data/lib/rubik/tools/truncator.rb +3 -3
  77. data/lib/rubik/version.rb +1 -1
  78. metadata +9 -1
@@ -8,11 +8,12 @@ require_relative "../platform"
8
8
  module Rubik
9
9
  module Sandbox
10
10
  class Runner
11
- attr_reader :root_dir, :driver, :allowed_external_dirs, :config, :guard
11
+ attr_reader :root_dir, :driver, :allowed_external_dirs, :config, :guard, :context
12
12
 
13
- def initialize(root_dir: Dir.pwd, allow_network: false, driver: nil, config: nil, allowed_external_dirs: [], guard: nil)
13
+ def initialize(root_dir: Dir.pwd, allow_network: false, driver: nil, config: nil, allowed_external_dirs: [], guard: nil, context: nil)
14
14
  @root_dir = File.expand_path(root_dir)
15
15
  @config = config
16
+ @context = context
16
17
  @preferred_driver = driver
17
18
  # Shared session guard (Composition provides it). Injected into every
18
19
  # driver_opts rebuild below so reconfigure! cycles never strand a
@@ -32,17 +33,31 @@ module Rubik
32
33
 
33
34
  reconfigure!
34
35
 
35
- return unless @config.respond_to?(:on_change)
36
-
37
- @config.on_change("sandbox") { reconfigure! }
38
- # Track explicit edits to the allow-list key itself. Once the user
39
- # has set this key at any scope, the config becomes authoritative:
40
- # reconfigure! recomputes config-sourced entries from scratch so
41
- # REMOVING a dir actually shrinks the live allow-list (the previous
42
- # union-based merge was monotonic and left stale dirs allowed).
43
- @config.on_change("workspace.allowed_external_dirs") do
44
- @allowed_dirs_config_touched = true
45
- reconfigure!
36
+ @cleanups = []
37
+ if @config.respond_to?(:on_change)
38
+ @cleanups << @config.on_change("sandbox") { reconfigure! }
39
+ # Track explicit edits to the allow-list key itself. Once the user
40
+ # has set this key at any scope, the config becomes authoritative:
41
+ # reconfigure! recomputes config-sourced entries from scratch so
42
+ # REMOVING a dir actually shrinks the live allow-list (the previous
43
+ # union-based merge was monotonic and left stale dirs allowed).
44
+ @cleanups << @config.on_change("workspace.allowed_external_dirs") do
45
+ @allowed_dirs_config_touched = true
46
+ reconfigure!
47
+ end
48
+ end
49
+
50
+ @context.on_dispose { dispose } if @context.respond_to?(:on_dispose)
51
+ end
52
+
53
+ # Unregisters accumulated configuration observers (AGENTS.md Ω Inverses).
54
+ def dispose
55
+ while (cleanup = @cleanups&.pop)
56
+ begin
57
+ cleanup.call
58
+ rescue StandardError => e
59
+ warn "[WARN] Sandbox::Runner cleanup failed: #{e.message}"
60
+ end
46
61
  end
47
62
  end
48
63
 
@@ -16,13 +16,24 @@ module Rubik
16
16
  DEFAULT_ROOT = "~/.rubik/rubikstorage"
17
17
 
18
18
  # Noktalı anahtar okuması her iki config şeklinde aynı çalışsın:
19
- # Rubik::Config#fetch noktalı yolları böler, düz Hash#fetch BÜTÜN
20
- # dizgiyi tek anahtar sayar — Hash için dig, diğerleri için fetch.
19
+ # Rubik::Config#fetch noktalı yolları böler, düz Hash için hem düz
20
+ # anahtar (config[key]) hem de iç içe Hash (dig) desteklenir —
21
+ # Hash için flat || dig, diğerleri için fetch, nil durumunda default.
21
22
  def config_get(config, key, default = nil)
22
23
  return default if config.nil?
23
24
 
24
25
  val = if config.is_a?(Hash)
25
- config.dig(*key.to_s.split("."))
26
+ if config.key?(key)
27
+ config[key]
28
+ elsif config.key?(key.to_s)
29
+ config[key.to_s]
30
+ else
31
+ begin
32
+ config.dig(*key.to_s.split("."))
33
+ rescue TypeError
34
+ nil
35
+ end
36
+ end
26
37
  elsif config.respond_to?(:fetch)
27
38
  config.fetch(key, nil)
28
39
  end
@@ -38,7 +38,7 @@ module Rubik
38
38
  return header << "_(empty — no #{type} entities yet)_\n" if summaries.empty?
39
39
 
40
40
  summaries.each do |s|
41
- title = s[:title].to_s.gsub("\\", "\\\\\\\\").gsub("|", "\\|").slice(0, 80)
41
+ title = s[:title].to_s.slice(0, 80).gsub(/[\\|]/) { |ch| "\\#{ch}" }
42
42
  header << "| #{s[:row]} | `#{s[:id]}` | #{s[:status]} | #{s[:updated_at]} | #{title} |\n"
43
43
  end
44
44
  header
@@ -260,11 +260,11 @@ module Rubik
260
260
 
261
261
  gap_ref = Vocabulary.recall_gap_ref(proposal["ref"])
262
262
  # Review bulgusu 2: smoke, gerçek recall'ın GÖRÜNÜR penceresiyle
263
- # koşulmalı — ilk RECALL_LIMIT kayıt. 6. sıradaki sayfa maestro'ya
263
+ # koşulmalı — ilk Recall::RECALL_LIMIT kayıt. 6. sıradaki sayfa maestro'ya
264
264
  # görünmüyorsa iska sayılmalı (öz-onarım döngüsü kör kalmasın).
265
265
  missed = checks.reject do |check|
266
- active_recall_hits(gate.store, query: check, type: Harness::RECALL_TYPES)
267
- .first(Harness::RECALL_LIMIT).any? { |r| r["id"] == page_id }
266
+ active_recall_hits(gate.store, query: check, type: Recall::RECALL_TYPES)
267
+ .first(Recall::RECALL_LIMIT).any? { |r| r["id"] == page_id }
268
268
  end
269
269
  if missed.empty?
270
270
  resolved = gate.store.get(type: "note", id: gap_ref)
@@ -13,10 +13,6 @@ module Rubik
13
13
  class Harness
14
14
  STOP = :__vakanuvis_stop__
15
15
  MAX_QUEUE = 200
16
- RECALL_LIMIT = 5
17
- RECALL_FALLBACK_LIMIT = 3
18
- RECALL_BODY_SLICE = 140
19
- RECALL_TYPES = ["memory", "wiki"].freeze
20
16
  # v2 §4-V4: damıtıcı kaynak disiplini — yalnız TAMAMLANMIŞ transcript'ler,
21
17
  # damıtıcının kendisi Hariç (özyineleme kirliliği: canlı depoda transcript satırları 'vakanuvis' etiketi taşır).
22
18
  SOURCE_TRANSCRIPT_LIMIT = 8
@@ -135,23 +131,10 @@ module Rubik
135
131
 
136
132
  # ---- talep düzlemi (maestro aracı buraya delege eder; K7) ---------
137
133
 
138
- # Tam deterministik, LLM'siz: Store#search_ranked BM25-lite sırası +
139
- # RECALL_TYPES kısıtı + ilk RECALL_LIMIT kayıt ⇒ aynı depo ⇒ aynı digest.
140
- # type: dizisi (v2 §4-V8) transcript/note gibi arama dışı tipleri hiç parse
141
- # etmez; sıralama politika kararına aittir — Store#search'in [type,row] sözleşmesi değişmez.
142
- def recall(query, types: RECALL_TYPES)
143
- q = query.to_s.strip
144
- raise ArgumentError, "recall: 'query' is required" if q.empty?
145
-
146
- allowed = Array(types).map(&:to_s)
147
- allowed = RECALL_TYPES if allowed.empty?
148
- hits = DistillGate.active_recall_hits(@store, query: q, type: allowed).first(RECALL_LIMIT)
149
- unless hits.empty?
150
- header = "Recalled #{hits.size} entit#{hits.size == 1 ? 'y' : 'ies'} for '#{AnnalWriter.one_line(q, 80)}':"
151
- return "#{header}\n#{hits.map { |r| recall_line(r) }.join("\n")}\nRead a full record with read_file(path: '<uri above>')."
152
- end
153
-
154
- relaxed_digest(q, allowed)
134
+ # Deterministik geri çağırma Recall düzleminde (recall.rb); burada
135
+ # yalnız delege — araç yüzeyi (K7) ve test ikizleri bu imzaya pinli.
136
+ def recall(query, types: Recall::RECALL_TYPES)
137
+ Recall.recall(@store, query, types: types)
155
138
  end
156
139
 
157
140
  def auto_digest? = @auto_digest
@@ -221,50 +204,6 @@ module Rubik
221
204
  shown.join(", ")
222
205
  end
223
206
 
224
- # v2 §4-V2 + issue #99 P2: AND boşluğu tek tip körlük değil — en yakın
225
- # kısmi eşleşmeler dürüstçe "(fallback)" damgasıyla sunulur (gerçek
226
- # eşleşme değildir), transcript izleri kapsam ipucu olarak sayılır. Ne
227
- # fallback ne transcript izi varsa bugünkü dil/terim yönlendirmesi birebir
228
- # döner (keyword-AND'da en sık neden TR sorgu ↔ EN gövde uyuşmazlığıdır;
229
- # yanlış "hemen yeniden kaydet" yönlendirmesi burada kesilir).
230
- def relaxed_digest(query, allowed)
231
- q = query.to_s.strip
232
- # Süpersede edilmiş sayılar "en yakın kısmi eşleşme" olarak
233
- # sunulmaz (review M1) — emekli bir sayfayı okumaya davet etmek,
234
- # issue #100'ün "iki kopya, biri bozuk" bulgusunun aynısıdır.
235
- relaxed = DistillGate.active_recall_hits(@store, query: q, type: allowed, require_all: false)
236
- .first(RECALL_FALLBACK_LIMIT)
237
- transcripts = @store.search(query: q, type: "transcript")
238
- if relaxed.empty? && transcripts.empty?
239
- return "No chronicled knowledge matches '#{AnnalWriter.one_line(q, 80)}'. Recall is keyword-AND: retry with fewer or other-language " \
240
- "terms first (e.g. the TR/EN Keywords: lines). If the knowledge is genuinely missing, record it (vakanuvis action 'record') or queue a digest."
241
- end
242
-
243
- parts = []
244
- # Başlık + read_file ayağı yalnız gerçek fallback izi varken
245
- # basılır (review CR#1: "yukarıdaki uri" diyecek uri yokken
246
- # olmayan bir talimat modele verilmesin).
247
- unless relaxed.empty?
248
- parts << "No exact keyword-AND match for '#{AnnalWriter.one_line(q, 80)}' — closest partial matches (fallback, not true matches):"
249
- parts.concat(relaxed.map { |r| "- (fallback) #{recall_line(r)}" })
250
- end
251
- unless transcripts.empty?
252
- parts << "#{transcripts.size} transcript entr#{transcripts.size == 1 ? 'y' : 'ies'} mention these terms — " \
253
- "the raw session logs may hold it; queue a digest to compile them."
254
- end
255
- parts << "If none of these help, retry with fewer or other-language terms (the TR/EN Keywords: lines), " \
256
- "record the knowledge, or queue a digest."
257
- parts << "Read a full record with read_file(path: '<uri above>')." unless relaxed.empty?
258
- parts.join("\n")
259
- end
260
-
261
- def first_body_line(record)
262
- slice = record["body"].to_s.lines.map(&:strip).reject(&:empty?).first.to_s.slice(0, RECALL_BODY_SLICE)
263
- slice.empty? ? "(no body)" : slice
264
- end
265
-
266
- def recall_line(record) = "- #{record['title']} [#{record['id']}] #{first_body_line(record)} — #{@store.uri_for(record['type'], record['id'])}"
267
-
268
207
  # Abonelik geri alımı dispatcher'a aittir (§1A: subscribe'a verilen context'e
269
208
  # unregister inverse'i kendisi bağlar); TURN aboneliği R7 knob'unun arkasındadır.
270
209
  def subscribe_events
@@ -202,8 +202,7 @@ module Rubik
202
202
  end
203
203
 
204
204
  def first_body_line(record)
205
- slice = record["body"].to_s.lines.map(&:strip).reject(&:empty?).first.to_s.slice(0, Harness::RECALL_BODY_SLICE)
206
- slice.empty? ? "(no body)" : slice
205
+ Recall.first_body_line(record)
207
206
  end
208
207
 
209
208
  # Aktif mem.* kartlarından deterministik [ref, row] sırasıyla en fazla
@@ -0,0 +1,84 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rubik
4
+ module Storage
5
+ module Vakanuvis
6
+ # Deterministik geri çağırma düzlemi: sorgu → digest dizgisi. LLM'siz,
7
+ # iş parçacığı içermeyen saf politika + üslup — Harness'in iş parçacığı
8
+ # çekirdeğinden (kuyruk + worker + olay dağıtımı) ayrı evi. Tüm
9
+ # RECALL_* sabitlerinin SSOT'u: Orientation ve DistillGate buradan
10
+ # okur, Harness'e geri dokunmaz.
11
+ module Recall
12
+ RECALL_LIMIT = 5
13
+ RECALL_FALLBACK_LIMIT = 3
14
+ RECALL_BODY_SLICE = 140
15
+ RECALL_TYPES = ["memory", "wiki"].freeze
16
+
17
+ module_function
18
+
19
+ # Tam deterministik, LLM'siz: Store#search_ranked BM25-lite sırası +
20
+ # RECALL_TYPES kısıtı + ilk RECALL_LIMIT kayıt ⇒ aynı depo ⇒ aynı digest.
21
+ # type: dizisi (v2 §4-V8) transcript/note gibi arama dışı tipleri hiç parse
22
+ # etmez; sıralama politika kararına aittir — Store#search'in [type,row] sözleşmesi değişmez.
23
+ def recall(store, query, types: RECALL_TYPES)
24
+ q = query.to_s.strip
25
+ raise ArgumentError, "recall: 'query' is required" if q.empty?
26
+
27
+ allowed = Array(types).map(&:to_s)
28
+ allowed = RECALL_TYPES if allowed.empty?
29
+ hits = DistillGate.active_recall_hits(store, query: q, type: allowed).first(RECALL_LIMIT)
30
+ unless hits.empty?
31
+ header = "Recalled #{hits.size} entit#{hits.size == 1 ? 'y' : 'ies'} for '#{AnnalWriter.one_line(q, 80)}':"
32
+ return "#{header}\n#{hits.map { |r| recall_line(store, r) }.join("\n")}\nRead a full record with read_file(path: '<uri above>')."
33
+ end
34
+
35
+ relaxed_digest(store, q, allowed)
36
+ end
37
+
38
+ # v2 §4-V2 + issue #99 P2: AND boşluğu tek tip körlük değil — en yakın
39
+ # kısmi eşleşmeler dürüstçe "(fallback)" damgasıyla sunulur (gerçek
40
+ # eşleşme değildir), transcript izleri kapsam ipucu olarak sayılır. Ne
41
+ # fallback ne transcript izi varsa bugünkü dil/terim yönlendirmesi birebir
42
+ # döner (keyword-AND'da en sık neden TR sorgu ↔ EN gövde uyuşmazlığıdır;
43
+ # yanlış "hemen yeniden kaydet" yönlendirmesi burada kesilir).
44
+ def relaxed_digest(store, query, allowed)
45
+ q = query.to_s.strip
46
+ # Süpersede edilmiş sayılar "en yakın kısmi eşleşme" olarak
47
+ # sunulmaz (review M1) — emekli bir sayfayı okumaya davet etmek,
48
+ # issue #100'ün "iki kopya, biri bozuk" bulgusunun aynısıdır.
49
+ relaxed = DistillGate.active_recall_hits(store, query: q, type: allowed, require_all: false)
50
+ .first(RECALL_FALLBACK_LIMIT)
51
+ transcripts = store.search(query: q, type: "transcript")
52
+ if relaxed.empty? && transcripts.empty?
53
+ return "No chronicled knowledge matches '#{AnnalWriter.one_line(q, 80)}'. Recall is keyword-AND: retry with fewer or other-language " \
54
+ "terms first (e.g. the TR/EN Keywords: lines). If the knowledge is genuinely missing, record it (vakanuvis action 'record') or queue a digest."
55
+ end
56
+
57
+ parts = []
58
+ # Başlık + read_file ayağı yalnız gerçek fallback izi varken
59
+ # basılır (review CR#1: "yukarıdaki uri" diyecek uri yokken
60
+ # olmayan bir talimat modele verilmesin).
61
+ unless relaxed.empty?
62
+ parts << "No exact keyword-AND match for '#{AnnalWriter.one_line(q, 80)}' — closest partial matches (fallback, not true matches):"
63
+ parts.concat(relaxed.map { |r| "- (fallback) #{recall_line(store, r)}" })
64
+ end
65
+ unless transcripts.empty?
66
+ parts << "#{transcripts.size} transcript entr#{transcripts.size == 1 ? 'y' : 'ies'} mention these terms — " \
67
+ "the raw session logs may hold it; queue a digest to compile them."
68
+ end
69
+ parts << "If none of these help, retry with fewer or other-language terms (the TR/EN Keywords: lines), " \
70
+ "record the knowledge, or queue a digest."
71
+ parts << "Read a full record with read_file(path: '<uri above>')." unless relaxed.empty?
72
+ parts.join("\n")
73
+ end
74
+
75
+ def first_body_line(record)
76
+ slice = record["body"].to_s.lines.map(&:strip).reject(&:empty?).first.to_s.slice(0, RECALL_BODY_SLICE)
77
+ slice.empty? ? "(no body)" : slice
78
+ end
79
+
80
+ def recall_line(store, record) = "- #{record['title']} [#{record['id']}] #{first_body_line(record)} — #{store.uri_for(record['type'], record['id'])}"
81
+ end
82
+ end
83
+ end
84
+ end
@@ -89,6 +89,7 @@ require_relative "vakanuvis/annal_writer"
89
89
  require_relative "vakanuvis/memory_steward"
90
90
  require_relative "vakanuvis/wiki_skeleton"
91
91
  require_relative "vakanuvis/distill_gate"
92
+ require_relative "vakanuvis/recall"
92
93
  require_relative "vakanuvis/job"
93
94
  require_relative "vakanuvis/gate"
94
95
  require_relative "vakanuvis/harness"
@@ -2,6 +2,8 @@
2
2
 
3
3
  require "pathname"
4
4
  require_relative "declaration"
5
+ require_relative "services" unless defined?(Rubik::Tools::Services)
6
+ require_relative "../coeffects" unless defined?(Rubik::Coeffects)
5
7
 
6
8
  module Rubik
7
9
  module Tools
@@ -42,6 +44,69 @@ module Rubik
42
44
  raise NotImplementedError
43
45
  end
44
46
 
47
+ # One home for model-supplied argument access: every builtin used to
48
+ # re-roll the string/symbol key
49
+ # normalization (and its coercion) by hand — ~110 sites. Lookup
50
+ # semantics, kept byte-compatible with the old hand-rolled chains:
51
+ # keys are tried in order, string key before symbol key per key;
52
+ # first non-nil wins (false falls through like nil, matching the
53
+ # ||-chains). When `type:`
54
+ # is given the coercion applies to the resolved value AND to
55
+ # `default:` (so `type: :integer` on an absent key still yields 0,
56
+ # matching the old `(args[k] || args[sk]).to_i` idiom).
57
+ #
58
+ # param(args, :path, type: :stripped_string, default: "")
59
+ # param(args, :offset, type: :integer)
60
+ # param(args, :target_content, :old_content, :old_str, :target) # alias chain
61
+ # param(args, :reload, type: :flag) # == true
62
+ def param(args, *keys, type: nil, default: nil)
63
+ raw = nil
64
+ if args
65
+ keys.each do |key|
66
+ str = key.to_s
67
+ raw = args[str] || args[str.to_sym]
68
+ break unless raw.nil?
69
+ end
70
+ end
71
+ value = raw.nil? ? default : raw
72
+ case type
73
+ when :integer then value.to_i
74
+ when :string then value.to_s
75
+ when :stripped_string then value.to_s.strip
76
+ when :flag then value == true
77
+ else value
78
+ end
79
+ end
80
+
81
+ # Single home for tool-side coeffect and service resolution (architecture
82
+ # review Candidate A2, issue #368). Unifies the 3 scattered tool-side
83
+ # dialects:
84
+ # 1. Coeffects.resolve(@runtime_context, KEY, @fallback)
85
+ # 2. @fallback || (ctx.respond_to?(:get) ? Coeffects.get(...) : nil)
86
+ # 3. @runtime_manager.context coeffect lookups
87
+ #
88
+ # Delegates directly to Tools::Services::COEFFECTS and Coeffects.get so
89
+ # no third resolution home is created. If the runtime context does not
90
+ # satisfy the coeffect, falls back to the explicitly passed `fallback`,
91
+ # or to an instance variable matching `@#{key}` if defined.
92
+ #
93
+ # task_mgr = service(:task_manager)
94
+ # harness = service(:pruner, @harness)
95
+ # asker = service(:subagent_question_asker)
96
+ def service(key, fallback = nil, ctx: nil)
97
+ effective_ctx = ctx || (defined?(@runtime_context) ? @runtime_context : nil)
98
+ effective_ctx ||= (@runtime_manager.context if defined?(@runtime_manager) && @runtime_manager.respond_to?(:context))
99
+
100
+ coeffect_key = Rubik::Tools::Services::COEFFECTS[key] || Rubik::Coeffects.canonical(key)
101
+ resolved = Rubik::Coeffects.get(effective_ctx, coeffect_key) if effective_ctx
102
+ return resolved unless nil.equal?(resolved)
103
+
104
+ return fallback unless nil.equal?(fallback)
105
+
106
+ ivar = :"@#{key}"
107
+ instance_variable_defined?(ivar) ? instance_variable_get(ivar) : nil
108
+ end
109
+
45
110
  # Normalizes a model-supplied path filter against the tool's root
46
111
  # directory: backslashes become slashes, "./" is stripped, and ABSOLUTE
47
112
  # paths (C:/…, /…) are relativized when they sit inside the root.
@@ -42,6 +42,12 @@ module Rubik
42
42
  @runtime_context = runtime_context
43
43
  end
44
44
 
45
+ # Subagent-plane rebind (ScopedRegistry delegate): definitions register
46
+ # against the INSTANCE's supervisor, not the root turn's.
47
+ def rebind_to(ctx)
48
+ self.class.new(supervisor: resolve_supervisor(nil, ctx), runtime_context: ctx)
49
+ end
50
+
45
51
  def execute(args = {})
46
52
  sup = resolve_supervisor(@supervisor, @runtime_context)
47
53
  return ToolOutput.error("SubagentSupervisor is not available in runtime context.") unless sup
@@ -51,10 +51,10 @@ module Rubik
51
51
  ring = resolve_dmesg
52
52
  return ToolOutput.error("Dmesg ring buffer is not available in runtime context.") unless ring
53
53
 
54
- limit = (args["limit"] || args[:limit] || 30).to_i
55
- level = args["level"] || args[:level]
56
- subsystem = args["subsystem"] || args[:subsystem]
57
- since_seq = args["since_seq"] || args[:since_seq]
54
+ limit = param(args, :limit, type: :integer, default: 30)
55
+ level = param(args, :level)
56
+ subsystem = param(args, :subsystem)
57
+ since_seq = param(args, :since_seq)
58
58
 
59
59
  records = ring.tail(limit, level: level, subsystem: subsystem, since_seq: since_seq)
60
60
  return "No kernel events found matching criteria." if records.empty?
@@ -67,7 +67,7 @@ module Rubik
67
67
  private
68
68
 
69
69
  def resolve_dmesg
70
- @dmesg || (@runtime_context.respond_to?(:get) ? Rubik::Coeffects.get(@runtime_context, Rubik::Coeffects::DMESG) : nil)
70
+ service(:dmesg)
71
71
  end
72
72
  end
73
73
  end
@@ -187,8 +187,7 @@ module Rubik
187
187
  private
188
188
 
189
189
  def execute_background(cmd)
190
- task_mgr = @task_manager ||
191
- (@runtime_context.respond_to?(:get) ? Rubik::Coeffects.get(@runtime_context, Rubik::Coeffects::TASK_MANAGER) : nil)
190
+ task_mgr = service(:task_manager)
192
191
  if task_mgr.nil?
193
192
  return Rubik::Tools::Result.new(tool_name: "run_command", status: :error,
194
193
  output: "TaskManager is not available to run commands in background.",
@@ -15,7 +15,7 @@ module Rubik
15
15
  DECLARATION = Declaration.new(
16
16
  name: "read_file", aliases: ["view_file", "read"],
17
17
  description: "Read content of a file from buffer or disk with 1-based line numbers (optional 1-based offset and line limit for paging)",
18
- risk: :read, archetypes: [:research, :coder],
18
+ risk: :read, archetypes: [:research, :coder], buffer_bound: true,
19
19
  params_schema: {
20
20
  type: "object",
21
21
  properties: {
@@ -41,7 +41,7 @@ module Rubik
41
41
  end
42
42
 
43
43
  def execute(args = {})
44
- path = (args["path"] || args[:path]).to_s.strip
44
+ path = param(args, :path, type: :stripped_string)
45
45
  # rubik:// sevk tek yerde: UriResolver (bilinmeyen şema/gramer reddi
46
46
  # nil döndürür ve buffer düzlemine düşer — bugünkü düşüş sözleşmesi).
47
47
  virt = UriResolver.resolve(path, ctx: @runtime_context, buffer_manager: @buffer_manager)
@@ -52,9 +52,9 @@ module Rubik
52
52
  path = clean.sub(%r{\A/([A-Za-z]:)}, '\1')
53
53
  end
54
54
 
55
- content = if args["reload"] == true || args[:reload] == true
55
+ content = if param(args, :reload, type: :flag)
56
56
  @buffer_manager.read(path, reload: true)
57
- elsif args["from_disk"] == true || args[:from_disk] == true
57
+ elsif param(args, :from_disk, type: :flag)
58
58
  @buffer_manager.read(path, from_disk: true)
59
59
  else
60
60
  @buffer_manager.read(path)
@@ -66,8 +66,8 @@ module Rubik
66
66
  return ToolOutput.error(DiagnosticReporter.render_file_not_found(path, candidates: candidates))
67
67
  end
68
68
 
69
- offset = (args["offset"] || args[:offset]).to_i
70
- limit = (args["limit"] || args[:limit]).to_i
69
+ offset = param(args, :offset, type: :integer)
70
+ limit = param(args, :limit, type: :integer)
71
71
  lines = content.lines
72
72
  return "[empty file (0 lines)]" if lines.empty?
73
73
 
@@ -90,7 +90,7 @@ module Rubik
90
90
  description: "Write full content to the in-memory buffer (does not write to disk until apply_buffer is called). " \
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
- risk: :write, archetypes: [:coder], write_grant: true, maestro_blocked: true,
93
+ risk: :write, archetypes: [:coder], write_grant: true, maestro_blocked: true, buffer_bound: true,
94
94
  params_schema: {
95
95
  type: "object",
96
96
  properties: {
@@ -106,8 +106,8 @@ module Rubik
106
106
  end
107
107
 
108
108
  def execute(args = {})
109
- path = (args["path"] || args[:path]).to_s.strip
110
- content = args["content"] || args[:content]
109
+ path = param(args, :path, type: :stripped_string)
110
+ content = param(args, :content)
111
111
 
112
112
  return ToolOutput.error("Error: `path` parameter is required.") if path.empty?
113
113
  unless Rubik::Buffer::PathValidator.valid?(path)
@@ -166,12 +166,12 @@ module Rubik
166
166
  end
167
167
 
168
168
  def context_index
169
- Rubik::Coeffects.resolve(@runtime_context, Rubik::Coeffects::CONTEXT_INDEX, @context_index)
169
+ service(:context_index, @context_index)
170
170
  end
171
171
 
172
172
  def execute(args = {})
173
- path_filter = args["path"] || args[:path]
174
- ext_filter = args["extension"] || args[:extension]
173
+ path_filter = param(args, :path)
174
+ ext_filter = param(args, :extension)
175
175
  idx = context_index
176
176
  return ToolOutput.error(IndexMessages::INDEX_UNAVAILABLE_MESSAGE) unless idx
177
177
 
@@ -236,7 +236,7 @@ module Rubik
236
236
  name: "replace_file_content", aliases: ["edit_file", "edit_chunk", "str_replace", "patch_file"],
237
237
  description: "Replace an exact chunk of code within an existing file. Requires exact verbatim matching of target_content " \
238
238
  "(including whitespace and indentation). Optional start_line and end_line narrow the search range.",
239
- risk: :write, archetypes: [:coder], write_grant: true, maestro_blocked: true,
239
+ risk: :write, archetypes: [:coder], write_grant: true, maestro_blocked: true, buffer_bound: true,
240
240
  params_schema: {
241
241
  type: "object",
242
242
  properties: {
@@ -258,18 +258,12 @@ module Rubik
258
258
  end
259
259
 
260
260
  def execute(args = {})
261
- path = (args["path"] || args[:path]).to_s.strip
262
- target = args["target_content"] || args[:target_content] ||
263
- args["old_content"] || args[:old_content] ||
264
- args["old_str"] || args[:old_str] ||
265
- args["target"] || args[:target]
266
- replacement = args["replacement_content"] || args[:replacement_content] ||
267
- args["new_content"] || args[:new_content] ||
268
- args["new_str"] || args[:new_str] ||
269
- args["replacement"] || args[:replacement]
270
- start_line = args["start_line"] || args[:start_line]
271
- end_line = args["end_line"] || args[:end_line]
272
- allow_multiple = args["allow_multiple"] == true || args[:allow_multiple] == true
261
+ path = param(args, :path, type: :stripped_string)
262
+ target = param(args, :target_content, :old_content, :old_str, :target)
263
+ replacement = param(args, :replacement_content, :new_content, :new_str, :replacement)
264
+ start_line = param(args, :start_line)
265
+ end_line = param(args, :end_line)
266
+ allow_multiple = param(args, :allow_multiple, type: :flag)
273
267
 
274
268
  return ToolOutput.error("Error: `path` parameter is required.") if path.empty?
275
269
  return ToolOutput.error("Error: `target_content` parameter is required.") if target.nil?
@@ -27,7 +27,7 @@ module Rubik
27
27
  "filesystem and it FAILED (the world drifted): re-inspect reality, then update the " \
28
28
  "entry (including status) with a normal patch — a stale rev also means the ledger " \
29
29
  "moved under you.",
30
- risk: :write, archetypes: [], write_grant: false,
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: {
33
33
  type: "object",
@@ -53,7 +53,7 @@ module Rubik
53
53
  "{\"rev\": N, \"ops\": [...]}.")
54
54
  end
55
55
 
56
- ledger = Rubik::Coeffects.resolve(@runtime_context, Rubik::Coeffects::GOAL_LEDGER, nil)
56
+ ledger = service(:goal_ledger)
57
57
  unless ledger
58
58
  return ToolOutput.error("Goal ledger is not available: no running !goal loop (or goal.ledger.enabled=false). " \
59
59
  "The ledger exists only while a goal loop runs; update it after each meaningful step.")
@@ -45,33 +45,33 @@ module Rubik
45
45
  end
46
46
 
47
47
  def context_index
48
- Rubik::Coeffects.resolve(@runtime_context, Rubik::Coeffects::CONTEXT_INDEX, @context_index)
48
+ service(:context_index, @context_index)
49
49
  end
50
50
 
51
51
  def buffer_manager
52
- Rubik::Coeffects.resolve(@runtime_context, Rubik::Coeffects::BUFFER_MANAGER, @buffer_manager)
52
+ service(:buffer_manager, @buffer_manager)
53
53
  end
54
54
 
55
55
  def execute(args = {})
56
56
  # Scrub before strip-driven string ops and result interpolation: an
57
57
  # invalid-UTF-8 query (model transcription artifact) must not raise
58
58
  # or leak broken bytes into the rendered tool output.
59
- query = Rubik::Platform.safe_utf8((args["query"] || args[:query]).to_s).strip
59
+ query = Rubik::Platform.safe_utf8(param(args, :query, type: :string)).strip
60
60
  return ToolOutput.error("Query parameter is required.") if query.empty?
61
61
 
62
- path_filter = (args["path"] || args[:path]).to_s.strip
63
- ext_filter = (args["extension"] || args[:extension]).to_s.strip
62
+ path_filter = param(args, :path, type: :stripped_string)
63
+ ext_filter = param(args, :extension, type: :stripped_string)
64
64
 
65
65
  path_filter, outside_error = BaseTool.normalize_path_filter(path_filter, @root_dir)
66
66
  if outside_error
67
67
  allowed = [{ path: @root_dir, primary: true }]
68
68
  idx = context_index
69
69
  idx.additional_roots.each { |r| allowed << { path: r, primary: false } } if idx.respond_to?(:additional_roots)
70
- return ToolOutput.error(DiagnosticReporter.render_traversal_blocked(args["path"] || args[:path], allowed_roots: allowed))
70
+ return ToolOutput.error(DiagnosticReporter.render_traversal_blocked(param(args, :path), allowed_roots: allowed))
71
71
  end
72
72
 
73
- case_sensitive = args["case_sensitive"] || args[:case_sensitive] || false
74
- max_results = (args["max_results"] || args[:max_results] || 50).to_i
73
+ case_sensitive = param(args, :case_sensitive, default: false)
74
+ max_results = param(args, :max_results, type: :integer, default: 50)
75
75
  max_results = 50 if max_results <= 0
76
76
 
77
77
  regex = regex_for(query, case_sensitive)
@@ -54,6 +54,12 @@ module Rubik
54
54
  @runtime_context = runtime_context
55
55
  end
56
56
 
57
+ # Subagent-plane rebind (ScopedRegistry delegate): a worker never pops a
58
+ # HUMAN dialog — it asks the maestro supervisor through the child ctx.
59
+ def rebind_to(ctx)
60
+ self.class.new(shell: nil, runtime_context: ctx)
61
+ end
62
+
57
63
  def execute(args = {})
58
64
  raw_questions = args["questions"] || args[:questions]
59
65
  raw_questions = [args] if raw_questions.nil? && (args["question"] || args[:question])
@@ -82,9 +88,7 @@ module Rubik
82
88
  # a subagent child context (ScopedRegistry rebind); the root-context
83
89
  # instance stays nil here and keeps the human-dialog behavior.
84
90
  def init0_asker
85
- return nil unless @runtime_context.respond_to?(:get)
86
-
87
- Rubik::Coeffects.get(@runtime_context, Rubik::Coeffects::SUBAGENT_QUESTION_ASKER)
91
+ service(:subagent_question_asker)
88
92
  end
89
93
 
90
94
  # One blocking round-trip for the whole batch: the maestro answers once and