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
@@ -94,13 +94,13 @@ module Rubik
94
94
  # Claim fence: cancellation may land between the entry guard and
95
95
  # this loop — a cancelled owner never launches.
96
96
  if owned_claim_blocked?(spec)
97
- cancel_spec!(spec, "owner task cancelled (^C)")
97
+ spec.cancel!("owner task cancelled (^C)")
98
98
  cancelled << spec
99
99
  next
100
100
  end
101
101
  next unless dependencies_evaluate(spec) == :ready
102
102
 
103
- spec.state = :spawning
103
+ spec.mark_spawning!
104
104
  claimed << spec
105
105
  end
106
106
  end
@@ -130,17 +130,17 @@ module Rubik
130
130
  # to death through the same fixed-point wave as a dead
131
131
  # predecessor.
132
132
  if owned_claim_blocked?(spec)
133
- cancel_spec!(spec, "owner task cancelled (^C)")
133
+ spec.cancel!("owner task cancelled (^C)")
134
134
  wave << spec
135
135
  next
136
136
  end
137
137
 
138
138
  case dependencies_evaluate(spec)
139
139
  when :ready
140
- spec.state = :spawning
140
+ spec.mark_spawning!
141
141
  claimed << spec
142
142
  when :dead
143
- cancel_spec!(spec, "predecessor failed or is no longer tracked")
143
+ spec.cancel!("predecessor failed or is no longer tracked")
144
144
  wave << spec
145
145
  end
146
146
  end
@@ -188,9 +188,9 @@ module Rubik
188
188
  verdicts = spec.deps.map do |d|
189
189
  deferred_pred = @deferred[d[:id]]
190
190
  return :dead if deferred_pred&.cancelled?
191
- return :dead if deferred_pred.nil? && @instances[d[:id]].nil? && (@finished || {})[d[:id]].nil?
191
+ return :dead if deferred_pred.nil? && @instances[d[:id]].nil? && @finished[d[:id]].nil?
192
192
 
193
- inst = @instances[d[:id]] || (@finished || {})[d[:id]]
193
+ inst = @instances[d[:id]] || @finished[d[:id]]
194
194
 
195
195
  if d[:type] == "FS"
196
196
  return :dead if inst&.failed?
@@ -229,12 +229,18 @@ module Rubik
229
229
  inst&.kill if killed_midflight
230
230
  killed_midflight ? [:cancelled, spec] : [:launched, inst]
231
231
  rescue ConcurrencyExceededError
232
- @monitor.synchronize { spec.state = :queued unless spec.cancelled? }
233
- [:queued, spec]
232
+ requeued = false
233
+ @monitor.synchronize do
234
+ requeued = !!spec.requeue!
235
+ end
236
+ # Truthful outcome: a cancelled spec was NOT re-queued — reporting
237
+ # [:queued, ...] made invoke_subagent render "QUEUED" for a spec
238
+ # that will never launch.
239
+ requeued ? [:queued, spec] : [:cancelled, spec]
234
240
  rescue StandardError => e
235
241
  cancelled = nil
236
242
  @monitor.synchronize do
237
- cancel_spec!(spec, "launch failed: #{e.class}: #{e.message}")
243
+ spec.cancel!("launch failed: #{e.class}: #{e.message}")
238
244
  cancelled = spec
239
245
  end
240
246
  announce_cancellations([cancelled])
@@ -253,7 +259,7 @@ module Rubik
253
259
  break if wave.empty?
254
260
 
255
261
  wave.each do |spec|
256
- cancel_spec!(spec, "predecessor failed or is no longer tracked")
262
+ spec.cancel!("predecessor failed or is no longer tracked")
257
263
  cancelled << spec
258
264
  end
259
265
  dead_ids = wave.map(&:id)
@@ -262,11 +268,6 @@ module Rubik
262
268
  cancelled
263
269
  end
264
270
 
265
- def cancel_spec!(spec, reason)
266
- spec.cancel_reason = reason
267
- spec.state = :cancelled
268
- end
269
-
270
271
  def announce_cancellations(specs)
271
272
  specs.each do |spec|
272
273
  Notices.emit(@event_bus, Notices::COMPLETED_EVENT,
@@ -293,7 +294,7 @@ module Rubik
293
294
  def refute_dead_dependencies!(specs)
294
295
  specs.each do |spec|
295
296
  spec.deps.each do |d|
296
- inst = @instances[d[:id]] || (@finished || {})[d[:id]]
297
+ inst = @instances[d[:id]] || @finished[d[:id]]
297
298
  if inst
298
299
  # Tek tüketici: atomlar yeterli — yeni bir Instance
299
300
  # predicate'ine gerek yok (settled? disposed'u dışlar,
@@ -309,7 +310,7 @@ module Rubik
309
310
  end
310
311
 
311
312
  def refute_unknown_dependencies!(specs)
312
- known = @instances.keys + (@finished || {}).keys + @deferred.keys + specs.map(&:id)
313
+ known = @instances.keys + @finished.keys + @deferred.keys + specs.map(&:id)
313
314
  specs.each do |spec|
314
315
  spec.deps.each do |d|
315
316
  next if known.include?(d[:id])
@@ -334,8 +335,7 @@ module Rubik
334
335
  def kill_locked(id, cascade, cancelled)
335
336
  if (spec = @deferred[id])
336
337
  if spec.spawning?
337
- spec.cancel_reason = "killed while launching"
338
- spec.state = :cancelled
338
+ spec.cancel!("killed while launching")
339
339
  else
340
340
  @deferred.delete(id)
341
341
  end
@@ -18,7 +18,7 @@ module Rubik
18
18
  return nil if sid.empty?
19
19
 
20
20
  @monitor.synchronize do
21
- (@instances.values + (@finished || {}).values).find do |inst|
21
+ (@instances.values + @finished.values).find do |inst|
22
22
  inst.respond_to?(:storage_id) && inst.storage_id.to_s == sid
23
23
  end
24
24
  end
@@ -6,6 +6,7 @@ require "time"
6
6
  require "fileutils"
7
7
  require_relative "../../platform"
8
8
  require_relative "../../security/redactor"
9
+ require_relative "../../storage/layout"
9
10
 
10
11
  module Rubik
11
12
  module Orchestrator
@@ -306,15 +307,8 @@ module Rubik
306
307
  value.length > limit ? "#{value[0, limit]}... [truncated #{value.length - limit} chars]" : value
307
308
  end
308
309
 
309
- def config_get(config, key, default)
310
- return default if config.nil?
311
-
312
- val = if config.is_a?(Hash)
313
- config[key] || config.dig(*key.split("."))
314
- elsif config.respond_to?(:fetch)
315
- config.fetch(key, nil)
316
- end
317
- val.nil? ? default : val
310
+ def config_get(config, key, default = nil)
311
+ Rubik::Storage::Layout.config_get(config, key, default)
318
312
  end
319
313
  end
320
314
  end
@@ -38,6 +38,15 @@ module Rubik
38
38
  disposed: []
39
39
  }.transform_values(&:freeze).freeze
40
40
 
41
+ # Attention vocabulary (the tool plane's "needs attention" classification,
42
+ # derived here so a state rename can never silently desync it — the tool
43
+ # layer hand-copied these until now). PARKED_STATES is the vocabulary's
44
+ # own words for the condvar-parked set; ATTENTION_STATES rides
45
+ # :waiting_input on top. A named owned constant, not a computation from
46
+ # TRANSITIONS — no clean derivation from the edges exists.
47
+ PARKED_STATES = [:paused_error, :waiting_budget, :budget_exhausted].freeze
48
+ ATTENTION_STATES = (PARKED_STATES + [:waiting_input]).freeze
49
+
41
50
  # --- Predicates: control-flow questions answer here, not at
42
51
  # consumers. All take the re-entrant monitor; callers composing
43
52
  # them under a held lock pay nothing extra, and external readers
@@ -74,7 +83,7 @@ module Rubik
74
83
 
75
84
  # Condvar-parked, reap-immune; the resume_all targets.
76
85
  def parked?
77
- @monitor.synchronize { error_paused? || awaiting_budget? }
86
+ @monitor.synchronize { PARKED_STATES.include?(@state) }
78
87
  end
79
88
 
80
89
  # The no-resurrection set (kill's race window included).
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "../../events"
3
4
  require_relative "../../platform"
4
5
  require_relative "budget"
5
6
 
@@ -11,16 +12,16 @@ module Rubik
11
12
  module Notices
12
13
  module_function
13
14
 
14
- # Bus event names
15
- COMPLETED_EVENT = :subagent_completed
15
+ # Bus event names; the cross-layer two read the Rubik::Events leaf.
16
+ COMPLETED_EVENT = Rubik::Events::SUBAGENT_COMPLETED
16
17
  BUDGET_EXHAUSTED_EVENT = :subagent_budget_exhausted
17
18
  COMPACTED_EVENT = :subagent_context_compacted
18
19
  AUTO_APPLY_FAILED_EVENT = :subagent_auto_apply_failed
19
20
  ERROR_PAUSED_EVENT = :subagent_error_paused
20
21
  QUESTION_EVENT = :subagent_question
21
- MESSAGE_EVENT = :subagent_message_to_parent
22
+ MESSAGE_EVENT = Rubik::Events::SUBAGENT_MESSAGE_TO_PARENT
22
23
 
23
- # Bus event name -> normalized notice kind.
24
+ # Bus event name -> normalized notice kind; MESSAGE_EVENT routes elsewhere.
24
25
  EVENTS = {
25
26
  COMPLETED_EVENT => :completed,
26
27
  BUDGET_EXHAUSTED_EVENT => :budget_exhausted,
@@ -0,0 +1,49 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rubik
4
+ module Orchestrator
5
+ module Subagent
6
+ # Pure pagination window arithmetic for subagent output streams
7
+ # (ResultArchive ≅ TranscriptReader — architecture scan 2026-11-06).
8
+ # Leaf helper: zero IO, zero locks, isolated and deterministic.
9
+ module Paging
10
+ Window = Struct.new(:cursor, :body, :next_cursor, :has_more, :total_chars, :returned_chars, keyword_init: true) do
11
+ def more? = has_more
12
+ alias_method :has_more?, :more?
13
+ end
14
+
15
+ module_function
16
+
17
+ # Clamps negative cursor values to 0.
18
+ def clamp_cursor(cursor)
19
+ [cursor.to_i, 0].max
20
+ end
21
+
22
+ # Computes the window slice for a given text and cursor/limit bounds.
23
+ # Returns nil if cursor exceeds total_chars.
24
+ def window(text, cursor:, limit:, default:, max:)
25
+ body = text.to_s
26
+ total = body.length
27
+ cur = clamp_cursor(cursor)
28
+ return nil if cur > total
29
+
30
+ size = limit.to_i
31
+ size = default if size <= 0
32
+ size = [size, max].min
33
+ slice = body[cur, size].to_s
34
+ nxt = cur + slice.length
35
+ has_more = nxt < total
36
+
37
+ Window.new(
38
+ cursor: cur,
39
+ body: slice,
40
+ next_cursor: has_more ? nxt : nil,
41
+ has_more: has_more,
42
+ total_chars: total,
43
+ returned_chars: slice.length
44
+ ).freeze
45
+ end
46
+ end
47
+ end
48
+ end
49
+ end
@@ -2,6 +2,7 @@
2
2
 
3
3
  require "json"
4
4
  require_relative "../../coeffects"
5
+ require_relative "admission_policy"
5
6
 
6
7
  module Rubik
7
8
  module Orchestrator
@@ -78,17 +79,10 @@ module Rubik
78
79
  )
79
80
  end
80
81
 
82
+ # Thin delegate: the grants formula lives in the AdmissionPolicy, so
83
+ # custom-type filters and the plane labels share one home.
81
84
  def tool_filter(grants)
82
- enabled = grants.freeze
83
- write_tools = Rubik::Tools::Catalog.write_grant_tools
84
- spawn_tools = Rubik::Tools::Catalog.spawn_tools
85
-
86
- lambda do |tool_name|
87
- next false if write_tools.include?(tool_name) && !enabled.include?("write")
88
- next false if spawn_tools.include?(tool_name) && !enabled.include?("subagent_spawn")
89
-
90
- true
91
- end
85
+ AdmissionPolicy.custom_tool_filter(grants)
92
86
  end
93
87
 
94
88
  def normalize_text(value, field, errors, allow_symbol: false)
@@ -43,7 +43,7 @@ module Rubik
43
43
  next unless inst.archive!
44
44
 
45
45
  dropped_steering << id if inst.respond_to?(:pending_redeploy_messages?) && inst.pending_redeploy_messages?
46
- (@finished ||= {})[id] = inst
46
+ @finished[id] = inst
47
47
  reaped << id
48
48
  end
49
49
  reaped.each { |id| @instances.delete(id) }
@@ -85,8 +85,6 @@ module Rubik
85
85
  # FIFO taşma: en eski mezar taşı evict edilir ve cleanup ile
86
86
  # :disposed'a çekilir (ctx zaten dispose'lu; cleanup no-op güvenli).
87
87
  def evict_overflow!
88
- return unless @finished
89
-
90
88
  while @finished.size > tombstone_limit
91
89
  _id, inst = @finished.shift
92
90
  inst&.cleanup
@@ -0,0 +1,99 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rubik
4
+ module Orchestrator
5
+ module Subagent
6
+ # The redeploy entry's supervisor-plane support: refusal reasons, the
7
+ # root-coeffect preflight, the SS release hook, and the spawn-parity
8
+ # transaction rollback (rollback_spawn! family, spawn_transaction.rb).
9
+ # The irreversible step — redeploy_for!'s history append + inbox
10
+ # drain — is NOT reverted; rollback restores PLACEMENT atomicity only:
11
+ # unit registration, roster placement, the fresh child ctx. The
12
+ # instance stays terminal-and-settled; a retry re-appends one
13
+ # "[New task]" line — bounded, benign.
14
+ #
15
+ # from_finished note: reaping archives before tombstoning, and archived
16
+ # instances refuse redeploy — a tombstoned lookup serves only the refusal
17
+ # message. The restoration arm is drift defense for future reap semantics.
18
+ module RedeployTransaction
19
+ # SS bırakma kancası (spawn ile aynı düzen): başarılı redeploy'un
20
+ # SONRASINDAKİ süpürme hatası, zaten koşan transaction'ı fail
21
+ # etmesin — spawn'ın "release failed after successful spawn"
22
+ # warn-paritesi.
23
+ def release_ready_after_redeploy!
24
+ release_ready!
25
+ rescue StandardError => e
26
+ Rubik::Log.warn(:orchestrator,
27
+ "subagent dependency release failed after successful redeploy (#{e.class}: #{e.message})")
28
+ end
29
+
30
+ # Reddetme gerekçesi durum-bazlı yönlendirme içerir: maestro doğru
31
+ # aksiyona (steer / wait / taze spawn) yönelsin.
32
+ def redeploy_refusal(id, inst)
33
+ return "Subagent '#{id}' not found." unless inst
34
+ return "Subagent '#{id}' is archived (reaped) — spawn a fresh subagent via invoke_subagent." if inst.archived?
35
+
36
+ if inst.settled?
37
+ "Subagent '#{id}' is still settling (completion handling in flight); retry shortly."
38
+ else
39
+ "Subagent '#{id}' is #{inst.state} with a live thread — steer it (send_message / extend_budget) or kill it first."
40
+ end
41
+ end
42
+
43
+ # Spawn preflights this before any reservation (resolve_profile_snapshot);
44
+ # redeploy discovered the same failure only in activate_instance! —
45
+ # i.e. AFTER the irreversible instance mutation. Root coeffects are
46
+ # checked against the root context; activation's own provides
47
+ # (asker/sender/cancellation) are exempt.
48
+ def preflight_redeploy_coeffects!(profile, type_name:)
49
+ unless profile
50
+ raise ReservedProfileError,
51
+ "No subagent archetype is available for '#{type_name}' (removed from the registry since spawn?)."
52
+ end
53
+
54
+ missing = (profile.requires || []).reject do |name|
55
+ SpawnSupervisor::CHILD_CONTEXT_COEFFECTS.include?(name) ||
56
+ !Rubik::Coeffects.get(@root_context, name).nil?
57
+ end
58
+ raise UnsatisfiedCoeffectsError.new(profile.name, missing) unless missing.empty?
59
+ end
60
+
61
+ # pre_existing_unit: the unit owned by the PREVIOUS lifecycle (if any).
62
+ # Only a unit this transaction minted (identity differs) is unregistered
63
+ # — a pre-mint failure must not desync the kernel board by stripping
64
+ # the historical unit the supervisor never touched here.
65
+ def rollback_redeploy!(inst:, child_ctx:, from_finished:, init_supervisor:, pre_existing_unit:)
66
+ if inst.unit && !inst.unit.equal?(pre_existing_unit) && init_supervisor.respond_to?(:unregister)
67
+ begin
68
+ init_supervisor.unregister(inst.unit)
69
+ rescue StandardError => e
70
+ Rubik::Log.warn(:orchestrator,
71
+ "subagent redeploy unit rollback failed for '#{inst.id}' (#{e.class}: #{e.message})")
72
+ end
73
+ end
74
+
75
+ begin
76
+ inst.fail_turn!("redeploy activation failed: worker could not start") unless inst.settled? || inst.disposed?
77
+ rescue StandardError => e
78
+ Rubik::Log.warn(:orchestrator,
79
+ "subagent redeploy state rollback failed for '#{inst.id}' (#{e.class}: #{e.message})")
80
+ end
81
+
82
+ # Restore the tombstone the deletion removed. For an @instances
83
+ # origin the map moves were no-ops — deleting here would LOSE
84
+ # the instance instead of restoring placement.
85
+ @instances.delete(inst.id) if from_finished && @instances[inst.id].equal?(inst)
86
+ @finished[inst.id] = inst if from_finished
87
+
88
+ begin
89
+ child_ctx&.dispose
90
+ rescue StandardError => e
91
+ Rubik::Log.warn(:orchestrator,
92
+ "subagent redeploy context rollback failed for '#{inst.id}' (#{e.class}: #{e.message})")
93
+ end
94
+ nil
95
+ end
96
+ end
97
+ end
98
+ end
99
+ end
@@ -1,7 +1,9 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "monitor"
4
+ require_relative "paging"
4
5
  require_relative "../../security/redactor"
6
+ require_relative "../../storage/layout"
5
7
  require_relative "../../uris"
6
8
 
7
9
  module Rubik
@@ -139,20 +141,15 @@ module Rubik
139
141
  private
140
142
 
141
143
  def page_for(entry, cursor, limit)
142
- body = entry.body
143
- total = body.length
144
- cur = [cursor.to_i, 0].max
145
- return missing(entry.ref, :cursor, "Cursor #{cur} exceeds the retained result length (#{total} chars). Use cursor 0.") if cur > total
146
-
147
- size = limit.to_i
148
- size = @page_chars if size <= 0
149
- size = [size, MAX_PAGE_CHARS].min
150
- text = body[cur, size].to_s
151
- nxt = cur + text.length
152
- has_more = nxt < total
144
+ win = Paging.window(entry.body, cursor: cursor, limit: limit, default: @page_chars, max: MAX_PAGE_CHARS)
145
+ unless win
146
+ cur = Paging.clamp_cursor(cursor)
147
+ return missing(entry.ref, :cursor, "Cursor #{cur} exceeds the retained result length (#{entry.body.length} chars). Use cursor 0.")
148
+ end
149
+
153
150
  Page.new(ref: entry.ref, storage_id: entry.storage_id, id: entry.id, run: entry.run, state: entry.state,
154
- body: text, cursor: cur, next_cursor: has_more ? nxt : nil, total_chars: total,
155
- returned_chars: text.length, has_more: has_more, redacted: true,
151
+ body: win.body, cursor: win.cursor, next_cursor: win.next_cursor, total_chars: win.total_chars,
152
+ returned_chars: win.returned_chars, has_more: win.has_more, redacted: true,
156
153
  retained_at: entry.retained_at, expires_at: entry.expires_at)
157
154
  end
158
155
 
@@ -180,15 +177,8 @@ module Rubik
180
177
  end
181
178
  end
182
179
 
183
- def config_get(config, key, default)
184
- return default if config.nil?
185
-
186
- val = if config.is_a?(Hash)
187
- config[key] || config.dig(*key.split("."))
188
- elsif config.respond_to?(:fetch)
189
- config.fetch(key, nil)
190
- end
191
- val.nil? ? default : val
180
+ def config_get(config, key, default = nil)
181
+ Rubik::Storage::Layout.config_get(config, key, default)
192
182
  end
193
183
  end
194
184
  end
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "reaper"
4
+ require_relative "redeploy_transaction"
4
5
 
5
6
  module Rubik
6
7
  module Orchestrator
@@ -88,6 +89,8 @@ module Rubik
88
89
  # imkânsız — bkz. activation.rb). provider/buffer/provider_gate/
89
90
  # storage_id/kimlik AYNEN KALIR (reuse'un kendisi bu).
90
91
  module RedeploySupervisor
92
+ include RedeployTransaction
93
+
91
94
  # `owner: :keep` (the default) keeps the instance's existing task
92
95
  # ownership; the tool plane passes the CURRENT turn's token so a
93
96
  # redeploy issued in this turn is cancellable with it (issue #125).
@@ -95,45 +98,48 @@ module Rubik
95
98
  prompt_str = prompt.to_s.strip
96
99
  raise ArgumentError, "Redeploy prompt cannot be empty" if prompt_str.empty?
97
100
 
101
+ lost_race = false # method scope: the block decides it, the tail reads it
98
102
  redeployed = @monitor.synchronize do
99
103
  key = id.to_s
100
- inst = @instances[key] || (@finished || {})[key]
104
+ inst = @instances[key] || @finished[key]
101
105
  raise ArgumentError, redeploy_refusal(key, inst) unless inst&.redeployable?
102
106
 
103
107
  eff_owner = owner == :keep ? inst.owner_task : owner
104
108
  refute_cancelled_owner!(eff_owner)
105
109
  validate_concurrency!
106
- child_ctx = extend_root_context!(:redeploy)
107
- profile = inst.profile_snapshot || @type_registry.get(inst.type_name)
108
- scoped_registry = build_scoped_registry(profile, child_ctx, inst.buffer_manager)
109
- return false unless inst.redeploy_for!(prompt: prompt_str, max_steps: (max_steps || @default_max_steps).to_i,
110
- context: child_ctx, tool_registry: scoped_registry,
111
- owner_task: eff_owner)
112
-
113
- @finished&.delete(inst.id)
114
- @instances[inst.id] = inst
115
- activate_instance!(inst, child_ctx: child_ctx, owner_token: eff_owner)
116
- end
117
- # Start-to-Start (SS) bırakma kancası: redeploy da bir başlangıçtır — taze :running
118
- # flip'i, bu id'yi Start-to-Start (SS) ile bekleyen kuyruk spesifikasyonlarını
119
- # bırakır (kilit DIŞINDA — emit kuralı; spawn ile aynı düzen).
120
- release_ready!
121
- redeployed
122
- end
123
-
124
- private
125
-
126
- # Reddetme gerekçesi durum-bazlı yönlendirme içerir: maestro doğru
127
- # aksiyona (steer / wait / taze spawn) yönelsin.
128
- def redeploy_refusal(id, inst)
129
- return "Subagent '#{id}' not found." unless inst
130
- return "Subagent '#{id}' is archived (reaped) — spawn a fresh subagent via invoke_subagent." if inst.archived?
131
-
132
- if inst.settled?
133
- "Subagent '#{id}' is still settling (completion handling in flight); retry shortly."
134
- else
135
- "Subagent '#{id}' is #{inst.state} with a live thread — steer it (send_message / extend_budget) or kill it first."
110
+ child_ctx = nil
111
+ pre_existing_unit = inst.unit
112
+ from_finished = @finished.key?(key)
113
+ eff_init = init_for_activation
114
+ begin
115
+ child_ctx = extend_root_context!(:redeploy)
116
+ profile = inst.profile_snapshot || @type_registry.get(inst.type_name)
117
+ preflight_redeploy_coeffects!(profile, type_name: inst.type_name)
118
+ scoped_registry = build_scoped_registry(profile, child_ctx, inst.buffer_manager)
119
+ lost_race = !inst.redeploy_for!(prompt: prompt_str, max_steps: (max_steps || @default_max_steps).to_i,
120
+ context: child_ctx, tool_registry: scoped_registry,
121
+ owner_task: eff_owner)
122
+ if lost_race
123
+ # Settle race (reaper archived / kill landed between the checks):
124
+ # the fresh child ctx was never bound into a worker — dispose it
125
+ # instead of leaking it into the parent accumulator.
126
+ child_ctx&.dispose
127
+ else
128
+ @finished.delete(inst.id)
129
+ @instances[inst.id] = inst
130
+ activate_instance!(inst, child_ctx: child_ctx, owner_token: eff_owner,
131
+ init_supervisor: eff_init)
132
+ end
133
+ rescue StandardError
134
+ rollback_redeploy!(inst: inst, child_ctx: child_ctx, from_finished: from_finished,
135
+ init_supervisor: eff_init, pre_existing_unit: pre_existing_unit)
136
+ raise
137
+ end
138
+ inst unless lost_race
136
139
  end
140
+ # SS bırakma kancası lost race'te atlanır: orijinal erken-return semantiği.
141
+ release_ready_after_redeploy! unless lost_race
142
+ lost_race ? false : redeployed
137
143
  end
138
144
  end
139
145
  end
@@ -78,7 +78,28 @@ module Rubik
78
78
  "ask_question tool — it blocks until the maestro answers or times out; ask only when the answer " \
79
79
  "truly changes your work.\n\n" \
80
80
  "Perform your assigned task with high precision and provide a structured synthesis report."
81
- @system_prompt && !@system_prompt.strip.empty? ? "#{base}\n\nCustom Instructions:\n#{@system_prompt}" : base
81
+ effective = @system_prompt && !@system_prompt.strip.empty? ? "#{base}\n\nCustom Instructions:\n#{@system_prompt}" : base
82
+
83
+ if @type_name == "self"
84
+ shell_pref = if @config.respond_to?(:fetch)
85
+ @config.fetch("sandbox.shell", "auto")
86
+ elsif @config.is_a?(Hash)
87
+ @config["sandbox.shell"] || "auto"
88
+ else
89
+ "auto"
90
+ end
91
+ if defined?(Rubik::Sandbox::ShellResolver)
92
+ env_line = Rubik::Sandbox::ShellResolver.environment_line(shell_pref)
93
+ effective = "#{effective}\n\n#{env_line}" if env_line && !env_line.empty?
94
+ end
95
+
96
+ if defined?(Rubik::Prompt::ContextBuilder)
97
+ protocol_xml = Rubik::Prompt::ContextBuilder.build_protocol_xml(@root_dir, config: @config)
98
+ effective = "#{effective}\n\n#{protocol_xml}" if protocol_xml && !protocol_xml.empty?
99
+ end
100
+ end
101
+
102
+ effective
82
103
  end
83
104
  end
84
105
  end
@@ -2,6 +2,7 @@
2
2
 
3
3
  require_relative "../../coeffects"
4
4
  require_relative "../../tools/catalog"
5
+ require_relative "admission_policy"
5
6
 
6
7
  module Rubik
7
8
  module Orchestrator
@@ -23,19 +24,50 @@ module Rubik
23
24
 
24
25
  def build(source_registry:, type_def:, child_ctx:, buffer:, parent_buffer:)
25
26
  return nil unless source_registry
27
+ raise ArgumentError, "ScopedRegistry.build requires a type_def; a nil type_def would grant every tool" unless type_def
26
28
 
27
29
  new_reg = Rubik::Tools::Registry.new(coeffect_ctx: child_ctx)
30
+ child_ctx.provide(Rubik::Coeffects::TOOL_REGISTRY, new_reg) if child_ctx.respond_to?(:provide)
28
31
  filter = type_def.tool_filter
32
+ unless filter
33
+ raise ArgumentError,
34
+ "type '#{type_def.name}' carries no tool_filter; a missing filter would grant every tool in the " \
35
+ "source registry. Set an explicit filter: ProfileContract.tool_filter(grants) for custom types, " \
36
+ "an archetype lambda for built-ins."
37
+ end
29
38
 
30
39
  source_registry.list.each do |tool|
31
40
  next if ROOT_ONLY_TOOLS.include?(tool.name)
32
- next unless filter.nil? || filter.call(tool.name)
33
41
 
34
- new_reg.register(bind_tool_buffer(tool, buffer, ctx: child_ctx, parent_buffer: parent_buffer))
42
+ origin = source_registry.origin(tool.name)
43
+ next unless tool_allowed?(filter, tool, origin, type_def)
44
+
45
+ new_reg.register(
46
+ bind_tool_buffer(tool, buffer, ctx: child_ctx, parent_buffer: parent_buffer),
47
+ origin: origin || :builtin
48
+ )
35
49
  end
36
50
  new_reg
37
51
  end
38
52
 
53
+ # Executor only: multi-arity filters own their whole decision; the
54
+ # shared arity-1 rule (name filter, then origin/risk) is the
55
+ # AdmissionPolicy's to answer.
56
+ def tool_allowed?(filter, tool, origin, type_def)
57
+ unless filter
58
+ raise ArgumentError,
59
+ "tool_allowed? requires a type_def with a tool_filter; a nil filter would grant every tool"
60
+ end
61
+
62
+ if filter.arity != 1
63
+ return filter.call(tool.name, tool, origin) ? true : false
64
+ end
65
+
66
+ return false unless filter.call(tool.name)
67
+
68
+ AdmissionPolicy.allowed?(tool.name, tool, origin, plane: AdmissionPolicy.plane_for(type_def))
69
+ end
70
+
39
71
  # Buffer-bound tools (rebuilt only when a branch buffer splits them
40
72
  # off the parent); everything else is context-rebind territory.
41
73
  # Membership is declared on each tool's Declaration (buffer_bound:)
@@ -99,7 +99,7 @@ module Rubik
99
99
  # next sequence number here and return it if activation rolls back.
100
100
  generated_id = reserved_id.nil?
101
101
  subagent_id = generated_id ? "subagent-#{@counter + 1}" : reserved_id.to_s
102
- id_in_use = @instances.key?(subagent_id) || (@finished || {}).key?(subagent_id)
102
+ id_in_use = @instances.key?(subagent_id) || @finished.key?(subagent_id)
103
103
  raise ArgumentError, "Subagent id '#{subagent_id}' is already in use." if id_in_use
104
104
 
105
105
  @counter += 1 if generated_id