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
@@ -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
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "../../coeffects"
4
+ require_relative "../../tools/catalog"
4
5
 
5
6
  module Rubik
6
7
  module Orchestrator
@@ -15,8 +16,10 @@ module Rubik
15
16
  # budayıcının masaları yalnız kök/maestro düzlemine aittir —
16
17
  # subagent kayıt defterlerine ('self' klonu dahil, çünkü onun
17
18
  # filtresi yalnız spawn setini dışlar) asla kopyalanmaz. Orkestrasyon
18
- # belleği tek elde kalır.
19
- ROOT_ONLY_TOOLS = ["prune_context", "vakanuvis", "update_goal_ledger"].freeze
19
+ # belleği tek elde kalır. Derived from the Declarations: a tool with
20
+ # no subagent archetype is orchestrator-plane-only by definition, so
21
+ # the projection cannot drift from the allowlists.
22
+ ROOT_ONLY_TOOLS = Rubik::Tools::Catalog.orchestrator_only_tools.freeze
20
23
 
21
24
  def build(source_registry:, type_def:, child_ctx:, buffer:, parent_buffer:)
22
25
  return nil unless source_registry
@@ -35,7 +38,10 @@ module Rubik
35
38
 
36
39
  # Buffer-bound tools (rebuilt only when a branch buffer splits them
37
40
  # off the parent); everything else is context-rebind territory.
38
- BUFFER_BOUND_TOOLS = ["read_file", "write_file", "replace_file_content", "apply_buffer"].freeze
41
+ # Membership is declared on each tool's Declaration (buffer_bound:)
42
+ # and projected by Catalog; the rebuild itself stays here because
43
+ # branch splitting is an orchestrator concern, not the tool's.
44
+ BUFFER_BOUND_TOOLS = Rubik::Tools::Catalog.buffer_bound_tools.freeze
39
45
 
40
46
  # Buffer rebinding must preserve runtime-context coeffect reads
41
47
  # (rubik://goal/state, rubik://storage, subagent transcripts resolve
@@ -63,29 +69,14 @@ module Rubik
63
69
  # subagent-plane message carries its REAL sender id to the maestro;
64
70
  # invoke/manage swap so a nested spawn resolves the INSTANCE's task
65
71
  # token (issue #125) instead of the root turn's.
66
- # Class-matched (not name-matched): a plugin/dynamic tool registered
67
- # under the same name keeps its own implementation in every plane.
72
+ # Each tool owns its rebind_to(ctx) (locality of concern); the
73
+ # registry only decides WHEN. Tools without rebind_to (plugins,
74
+ # dynamic tools registered under the same name) keep their own
75
+ # implementation in every plane.
68
76
  def rebind_to_context(tool, ctx)
69
77
  return tool unless ctx.respond_to?(:get)
70
78
 
71
- case tool
72
- when Rubik::Tools::AskQuestionTool
73
- Rubik::Tools::AskQuestionTool.new(shell: nil, runtime_context: ctx)
74
- when Rubik::Tools::SendMessageTool
75
- Rubik::Tools::SendMessageTool.new(runtime_context: ctx)
76
- when Rubik::Tools::InvokeSubagentTool
77
- Rubik::Tools::InvokeSubagentTool.new(supervisor: supervisor_for(ctx), runtime_context: ctx)
78
- when Rubik::Tools::ManageSubagentsTool
79
- Rubik::Tools::ManageSubagentsTool.new(supervisor: supervisor_for(ctx), runtime_context: ctx)
80
- when Rubik::Tools::DefineSubagentTool
81
- Rubik::Tools::DefineSubagentTool.new(supervisor: supervisor_for(ctx), runtime_context: ctx)
82
- else
83
- tool
84
- end
85
- end
86
-
87
- def supervisor_for(ctx)
88
- Rubik::Coeffects.get(ctx, Rubik::Coeffects::SUBAGENT_SUPERVISOR)
79
+ tool.respond_to?(:rebind_to) ? tool.rebind_to(ctx) : tool
89
80
  end
90
81
  end
91
82
  end
@@ -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
@@ -115,13 +115,23 @@ module Rubik
115
115
  prov = provider if provider
116
116
 
117
117
  context_limit = @config.respond_to?(:fetch) ? @config.fetch("context.max_tokens", 32_768) : 32_768
118
+ effective_steps = (max_steps || @default_max_steps).to_i
119
+ child_config = if @config.is_a?(Rubik::Config)
120
+ @config.extend(
121
+ "agent.max_steps" => effective_steps,
122
+ "context.max_tokens" => context_limit
123
+ )
124
+ else
125
+ @config
126
+ end
127
+ child_ctx.provide(Rubik::Coeffects::CONFIG, child_config) if child_ctx.respond_to?(:provide) && defined?(Rubik::Coeffects::CONFIG)
118
128
 
119
129
  Instance.new(
120
130
  id: subagent_id, parent_id: parent_id, role: role_str, type_name: profile_snapshot.name,
121
131
  prompt: prompt_str, system_prompt: profile_snapshot.effective_system_prompt, workspace: workspace,
122
132
  model: effective_model, context: child_ctx, tool_registry: scoped_registry,
123
- provider: prov, buffer_manager: effective_buffer, max_steps: (max_steps || @default_max_steps).to_i,
124
- provider_gate: @provider_gate, root_dir: @root_dir, config: @config,
133
+ provider: prov, buffer_manager: effective_buffer, max_steps: effective_steps,
134
+ provider_gate: @provider_gate, root_dir: @root_dir, config: child_config,
125
135
  context_limit: context_limit, event_bus: @event_bus,
126
136
  transcript_storage: absorb_storage, owner_task: owner,
127
137
  prompt_reconstructible: prompt_reconstructible, profile_snapshot: profile_snapshot
@@ -66,6 +66,10 @@ module Rubik
66
66
 
67
67
  @type_registry = TypeRegistry.new(default_context: @root_context)
68
68
  @instances = {}
69
+ # Tombstone table (reaped executions) is born here beside its
70
+ # sibling maps — ReaperSupervisor writes it, every reader may
71
+ # assume it is initialized.
72
+ @finished = {}
69
73
  @deferred = {}
70
74
  @monitor = Monitor.new
71
75
  @wait_cond = @monitor.new_cond
@@ -95,7 +99,7 @@ module Rubik
95
99
  @root_context.register_disposable { shutdown_all } if @root_context.respond_to?(:register_disposable)
96
100
  end
97
101
 
98
- def get(id) = @monitor.synchronize { @instances[id.to_s] || (@finished ||= {})[id.to_s] || queued_spec(id.to_s) }
102
+ def get(id) = @monitor.synchronize { @instances[id.to_s] || @finished[id.to_s] || queued_spec(id.to_s) }
99
103
 
100
104
  def extend_budget(id, steps = Budget::DEFAULT_GRANT_STEPS)
101
105
  inst = get(id)
@@ -125,7 +129,7 @@ module Rubik
125
129
 
126
130
  def list(parent_id: nil)
127
131
  @monitor.synchronize do
128
- items = @instances.values + (@finished ||= {}).values + @deferred.values
132
+ items = @instances.values + @finished.values + @deferred.values
129
133
  items = items.select { |i| i.parent_id == parent_id.to_s } if parent_id
130
134
  items.sort_by { |i| i.started_at || Time.at(0) }
131
135
  end
@@ -51,7 +51,7 @@ module Rubik
51
51
  end
52
52
 
53
53
  remaining = @monitor.synchronize do
54
- (@instances.values + (@finished || {}).values + requested.values).uniq.select do |inst|
54
+ (@instances.values + @finished.values + requested.values).uniq.select do |inst|
55
55
  owned_by?(inst, token) && !cancellation_settled?(inst)
56
56
  end
57
57
  end
@@ -97,7 +97,7 @@ module Rubik
97
97
  def cancel_queued_specs(token)
98
98
  queued = @monitor.synchronize do
99
99
  specs = @deferred.values.select { |spec| spec.respond_to?(:owner) && spec.owner.equal?(token) }
100
- specs.each { |spec| cancel_spec!(spec, "owner task cancelled (^C)") }
100
+ specs.each { |spec| spec.cancel!("owner task cancelled (^C)") }
101
101
  specs
102
102
  end
103
103
  announce_cancellations(queued)
@@ -1,7 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require_relative "../../tools/truncator"
4
- require_relative "../../tools/result"
3
+ require_relative "../../tools/result_normalizer"
5
4
  require_relative "../tool_timeout"
6
5
 
7
6
  module Rubik
@@ -11,7 +10,8 @@ module Rubik
11
10
  # every outcome — Result-backed, status-bearing, plain string, missing
12
11
  # tool, or raised error — is normalized into the Result contract so
13
12
  # status / exit_code / metadata survive truncation and reach the
14
- # canonical history row. Same classification as the root StepExecutor,
13
+ # canonical history row. Classification itself lives in
14
+ # Tools::ResultNormalizer, shared verbatim with the root StepExecutor,
15
15
  # so the two channels cannot drift.
16
16
  module ToolDispatch
17
17
  def dispatch_subagent_tool(tool, name, args)
@@ -22,10 +22,7 @@ module Rubik
22
22
  canonical_name: tool.respond_to?(:name) ? tool.name : name) do
23
23
  tool.execute(args)
24
24
  end
25
- max_chars = (cfg&.fetch("tools.max_output_chars", Rubik::Tools::Truncator::DEFAULT_MAX_CHARS) || Rubik::Tools::Truncator::DEFAULT_MAX_CHARS).to_i
26
- max_lines = (cfg&.fetch("tools.max_output_lines", Rubik::Tools::Truncator::DEFAULT_MAX_LINES) || Rubik::Tools::Truncator::DEFAULT_MAX_LINES).to_i
27
- strategy = Rubik::Tools::Truncator.resolve_strategy(cfg&.fetch("tools.truncation_strategy", Rubik::Tools::Truncator::DEFAULT_STRATEGY))
28
- normalize_tool_result(raw, name, max_chars: max_chars, max_lines: max_lines, strategy: strategy)
25
+ normalize_tool_result(raw, name)
29
26
  rescue Rubik::Orchestrator::ToolTimeout::BudgetExceeded => e
30
27
  Rubik::Orchestrator::ToolTimeout.emit_timeout_event(tool_name: name, budget_seconds: e.budget_seconds,
31
28
  elapsed_seconds: e.elapsed_seconds, context: @context)
@@ -37,48 +34,14 @@ module Rubik
37
34
 
38
35
  private
39
36
 
40
- def normalize_tool_result(raw, name, max_chars:, max_lines:, strategy: Rubik::Tools::Truncator::DEFAULT_STRATEGY)
41
- if raw.is_a?(Rubik::Tools::Result)
42
- trunc = Rubik::Tools::Truncator.truncate(raw.output, max_chars: max_chars, max_lines: max_lines, strategy: strategy)
43
- # Truncation only shortens the display text — status, exit code,
44
- # metadata and the original truncation flag all survive it.
45
- first_line = raw.output.to_s.lines.first.to_s.strip
46
- Rubik::Tools::Result.new(tool_name: raw.tool_name.to_s.empty? ? name : raw.tool_name,
47
- status: raw.status,
48
- error: raw.error || (raw.error? ? first_line : nil), exit_code: raw.exit_code,
49
- output: trunc[:text], duration_ms: raw.duration_ms,
50
- truncated: raw.truncated || trunc[:truncated], metadata: raw.metadata)
51
- elsif raw.respond_to?(:status) && raw.respond_to?(:output)
52
- out_str = raw.output.to_s
53
- trunc = Rubik::Tools::Truncator.truncate(out_str, max_chars: max_chars, max_lines: max_lines, strategy: strategy)
54
- first_line = out_str.lines.first.to_s.strip
55
- status = raw.status.to_sym
56
- Rubik::Tools::Result.new(tool_name: name, status: status,
57
- error: (raw.respond_to?(:error) && raw.error) || (status == :error ? first_line : nil),
58
- output: trunc[:text], truncated: trunc[:truncated],
59
- exit_code: raw.respond_to?(:exit_code) ? raw.exit_code : nil,
60
- metadata: raw.respond_to?(:metadata) ? raw.metadata : {})
61
- else
62
- out_str = raw.to_s
63
- trunc = Rubik::Tools::Truncator.truncate(out_str, max_chars: max_chars, max_lines: max_lines, strategy: strategy)
64
- status = classify_raw_string(raw, out_str)
65
- Rubik::Tools::Result.new(tool_name: name, status: status,
66
- error: status == :error ? out_str.lines.first.to_s.strip : nil,
67
- output: trunc[:text], truncated: trunc[:truncated])
68
- end
69
- end
70
-
71
- # Root-parity string classification (arch scan card 5, review F1): the
72
- # same lexicon as StepExecutor#normalize_raw_output's else branch —
73
- # error?/failed? predicates, then the shared ERROR_PREFIXES table.
74
- # Without this, a bare "Error: ..." string reads status=ok in subagent
75
- # history while the root plane honestly reports :error.
76
- def classify_raw_string(raw, out_str)
77
- return :error if raw.respond_to?(:error?) && raw.error?
78
- return :error if raw.respond_to?(:failed?) && raw.failed?
79
- return :error if raw.is_a?(String) && Rubik::Orchestrator::StepExecutor::ERROR_PREFIXES.any? { |pfx| out_str.start_with?(pfx) }
80
-
81
- :ok
37
+ # Thin delegator: carrier classification and truncation limits live
38
+ # in Tools::ResultNormalizer — the single home both orchestrator
39
+ # planes share, so the channels cannot drift. The
40
+ # subagent plane passes no call_id/duration_ms (nothing measured
41
+ # here); wrapping stays local so a normalize bug is contained into an
42
+ # error result by dispatch_subagent_tool's rescue.
43
+ def normalize_tool_result(raw, name)
44
+ Rubik::Tools::ResultNormalizer.normalize(raw, tool_name: name, config: @config)
82
45
  end
83
46
 
84
47
  def error_result(name, text, error: nil)
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "digest"
4
+ require_relative "paging"
4
5
  require_relative "transcript_formatter"
5
6
  require_relative "../../uris"
6
7
 
@@ -21,8 +22,12 @@ module Rubik
21
22
  # execution state, and never touch the workspace gate: live comes from
22
23
  # the instance roster, disk from the execution's own storage-id path.
23
24
  module TranscriptReader
24
- # A live execution whose memory snapshot is the freshest source.
25
- ACTIVE_STATES = ["pending", "running", "waiting_input", "waiting_budget", "paused_error", "canceling", "queued"].freeze
25
+ # A live execution whose memory snapshot is the freshest source. The
26
+ # instance vocabulary only — "queued" was dead data here: an Instance
27
+ # can never hold :queued (TRANSITIONS has no such state), and the
28
+ # tool plane resolves queued specs to their own handling before
29
+ # read_transcript is ever reached.
30
+ ACTIVE_STATES = ["pending", "running", "waiting_input", "waiting_budget", "paused_error", "canceling"].freeze
26
31
 
27
32
  # Page size stays under the tool-output truncation ceiling (head_tail
28
33
  # would otherwise eat the middle of a page); the hard cap bounds a
@@ -135,20 +140,16 @@ module Rubik
135
140
  "Start a new read at cursor 0 to get a consistent snapshot.")
136
141
  end
137
142
 
138
- total = text.length
139
- cur = [cursor.to_i, 0].max
140
- return missing(sid, :cursor, "Cursor #{cur} exceeds the transcript length (#{total} chars). Use cursor 0.") if cur > total
143
+ win = Paging.window(text, cursor: cursor, limit: limit, default: DEFAULT_PAGE_CHARS, max: MAX_PAGE_CHARS)
144
+ unless win
145
+ cur = Paging.clamp_cursor(cursor)
146
+ return missing(sid, :cursor, "Cursor #{cur} exceeds the transcript length (#{text.length} chars). Use cursor 0.")
147
+ end
141
148
 
142
- size = limit.to_i
143
- size = DEFAULT_PAGE_CHARS if size <= 0
144
- size = [size, MAX_PAGE_CHARS].min
145
- body = text[cur, size].to_s
146
- nxt = cur + body.length
147
- has_more = nxt < total
148
149
  Page.new(storage_id: sid, id: instance&.id, source: source, snapshot: token,
149
150
  state: instance.respond_to?(:state) ? instance.state&.to_s : nil, persisted: source == "disk",
150
- body: body, cursor: cur, next_cursor: has_more ? nxt : nil, total_chars: total,
151
- returned_chars: body.length, has_more: has_more)
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)
152
153
  end
153
154
 
154
155
  def missing(storage_id, reason, message)
@@ -56,13 +56,18 @@ module Rubik
56
56
  end
57
57
 
58
58
  # Registry-canonical finish detection: a call is the finish call when
59
- # the registry resolves it to the finish tool — an unregistered case
60
- # variant ("Finish") downcases to finish instead of dispatching an
61
- # unknown tool. A nil registry degrades to the downcase compare.
59
+ # the registry resolves it to a terminal tool (Declaration terminal:,
60
+ # projected by Catalog). The name compare stays as the duck-typed
61
+ # fallback — fake/dynamic registries can resolve plain objects whose
62
+ # class carries no Declaration (a terminal?-less "finish" must still
63
+ # complete the turn, or the loop waits forever); an unregistered case
64
+ # variant ("Finish") downcases to finish too.
62
65
  def finish_call?(tool_registry, tool_call)
63
66
  t_name = tool_call["tool"] || tool_call[:tool]
64
67
  resolved = tool_registry.respond_to?(:get) ? tool_registry.get(t_name) : nil
65
- (resolved ? resolved.name : t_name.to_s.downcase) == "finish"
68
+ return true if resolved.respond_to?(:terminal?) && resolved.terminal?
69
+
70
+ (resolved ? resolved.name : t_name).to_s.downcase == "finish"
66
71
  end
67
72
  end
68
73
 
@@ -63,10 +63,11 @@ module Rubik
63
63
 
64
64
  ctx.out.puts "=== Subagent Process Hierarchy (#{instances.size} tracked, #{sup.active_count} active) ==="
65
65
  instances.each do |inst|
66
+ # A :spawning spec is mid-launch, not ended — ask spec vocabulary directly.
66
67
  dur = if inst.running?
67
68
  "up #{inst.uptime.round(1)}s"
68
- elsif inst.state == :queued
69
- "queued (waiting on: #{inst.depends_on.join(', ')})"
69
+ elsif inst.respond_to?(:spawning?) && (inst.queued? || inst.spawning?)
70
+ "queued/launching (waiting on: #{inst.depends_on.join(', ')})"
70
71
  else
71
72
  "ended (#{inst.uptime.round(1)}s)"
72
73
  end
@@ -379,6 +379,16 @@ module Rubik
379
379
  ctx.out.puts "[Rubik::Allow] Added allowed external directory: #{expanded} (Mode: #{mode_str}) [#{Base.scope_label(scope)}]."
380
380
  end
381
381
 
382
+ OPERATOR_ONLY_CONFIG_PREFIXES = [
383
+ "security.",
384
+ "sandbox.",
385
+ "subagents.",
386
+ "plugins.",
387
+ "lsp.servers.",
388
+ "workspace.allow_external_writes",
389
+ "tools.circuit_breaker."
390
+ ].freeze
391
+
382
392
  private_class_method def self.register_config_command(shell)
383
393
  shell.register_command("config", description: "Get, set, or view runtime configuration (set|get|list|path)",
384
394
  usage: USAGE_CONFIG, audience: :both) do |args, ctx|
@@ -407,14 +417,10 @@ module Rubik
407
417
  val = clean_args[2..]&.join(" ")
408
418
  if key.nil? || key.empty? || val.nil? || val.empty?
409
419
  ctx.out.puts "Usage: !config set <key> <val> [--project|--global]"
410
- elsif ctx.agent_caller && key.start_with?("security.", "sandbox.", "subagents.")
411
- # Paket D fail-closed: the agent cannot grant itself command
412
- # allowlist entries or toggle sandbox enforcement. subagents.*
413
- # da operatör-only: ajan kendi tasmasını (maestro_gate,
414
- # concurrency, reap grace) exec_repl_command ile çözemez —
415
- # kapı canlı config okur, self-unlock yolu bu yüzden kapalı.
416
- ctx.out.puts "Security Error: keys under 'security.*' and 'sandbox.*' are operator-only " \
417
- "(mutated via !allow-cmd / !allow-dir as the human operator)."
420
+ elsif ctx.agent_caller && OPERATOR_ONLY_CONFIG_PREFIXES.any? { |p| key.start_with?(p) }
421
+ # Security boundary: agents cannot alter security, sandbox, subagent governance,
422
+ # plugins (arbitrary code execution), LSP binary commands, or external write policies.
423
+ ctx.out.puts "Security Error: configuration key '#{key}' is operator-only and cannot be altered by autonomous agents."
418
424
  else
419
425
  res = ctx.config.set(key, val, persist: scope)
420
426
  next if Base.report_persist_failure(ctx, res, scope)
@@ -151,6 +151,17 @@ module Rubik
151
151
  Rubik.runtime_manager = @runtime_manager
152
152
  @overlay_storage.load_all(self, @runtime_manager)
153
153
  @config_cleanups = ConfigWiring.wire(self)
154
+ if @runtime_manager&.context.respond_to?(:on_dispose)
155
+ @runtime_manager.context.on_dispose do
156
+ while (cleanup = @config_cleanups&.pop)
157
+ begin
158
+ cleanup.call
159
+ rescue StandardError => e
160
+ warn "[WARN] Config cleanup failed: #{e.message}"
161
+ end
162
+ end
163
+ end
164
+ end
154
165
  # Phase 5 built the tool registry; the skill tool's epoch (its
155
166
  # revertible registration + inverse) opens on the manager's own
156
167
  # sub-context only after config wiring so enable/disable knobs react.
@@ -1,5 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "../../storage/layout"
4
+
3
5
  module Rubik
4
6
  module REPL
5
7
  module Pruner
@@ -66,15 +68,8 @@ module Rubik
66
68
  # Noktalı anahtar okuması iki config şeklinde de aynı çalışsın
67
69
  # (maestro_gate.rb:38-40 düzeni): Rubik::Config#fetch noktalı yolu
68
70
  # böler, düz Hash hepsini tek anahtar sayar → dig'e düş.
69
- def config_get(config, key, default)
70
- return default if config.nil?
71
-
72
- val = if config.is_a?(Hash)
73
- config.dig(*key.to_s.split("."))
74
- elsif config.respond_to?(:fetch)
75
- config.fetch(key, nil)
76
- end
77
- val.nil? ? default : val
71
+ def config_get(config, key, default = nil)
72
+ Rubik::Storage::Layout.config_get(config, key, default)
78
73
  end
79
74
  end
80
75
  end
@@ -239,7 +239,8 @@ module Rubik
239
239
  name: :sandbox_runner,
240
240
  builder: lambda do |s|
241
241
  Rubik::Sandbox::Runner.new(root_dir: s.root_dir, config: s[:config],
242
- allowed_external_dirs: s[:allowed_ext_dirs], guard: s[:guard])
242
+ allowed_external_dirs: s[:allowed_ext_dirs], guard: s[:guard],
243
+ context: s[:runtime_manager]&.context)
243
244
  end,
244
245
  provide: Rubik::Coeffects::SANDBOX_RUNNER
245
246
  ),
@@ -74,6 +74,8 @@ module Rubik
74
74
  def provide(name, service)
75
75
  key = name.to_s.downcase
76
76
  @monitor.synchronize do
77
+ raise ContextDisposedError, "Cannot provide '#{name}' on a disposed context." if @disposed
78
+
77
79
  already_provided = @services.key?(key)
78
80
  @services[key] = service
79
81
  return if already_provided
@@ -219,6 +221,10 @@ module Rubik
219
221
  protected :prune_child
220
222
 
221
223
  def dispose
224
+ return if disposed?
225
+
226
+ # Resolve dmesg outside monitor to preserve parent→child lock order (F3).
227
+ dmesg = resolve_dmesg
222
228
  parent = nil
223
229
  deferred_interrupt = nil
224
230
  @monitor.synchronize do
@@ -230,7 +236,6 @@ module Rubik
230
236
  # (record_deferred_signal) survive into the final
231
237
  # last_dispose_errors instead of being wiped by this reset.
232
238
  @last_dispose_errors = []
233
- dmesg = resolve_dmesg
234
239
  # Counted before the cascade: disposing children prune their
235
240
  # inverses from our accumulator (pre-cascade size is what the
236
241
  # "beginning" log reports).
@@ -90,12 +90,13 @@ module Rubik
90
90
  true
91
91
  rescue StandardError => e
92
92
  # Atomic Rollback on Error: unwind partial inverses immediately
93
- @sub_context&.dispose
94
- @sub_context = nil
95
- @instance = nil
96
- @state = :failed
97
- @last_error = e
93
+ rollback_activation!(e)
98
94
  false
95
+ rescue Exception => e # rubocop:disable Lint/RescueException
96
+ # Failure Reversibility on fatal exceptions/signals (Interrupt, SystemExit):
97
+ # execute partial inverses immediately to restore the environment, then re-raise (AGENTS.md §1.A).
98
+ rollback_activation!(e)
99
+ raise
99
100
  end
100
101
  end
101
102
 
@@ -130,6 +131,17 @@ module Rubik
130
131
  def build_instance(_sub_context, _config)
131
132
  nil
132
133
  end
134
+
135
+ private
136
+
137
+ def rollback_activation!(error)
138
+ ctx = @sub_context
139
+ @sub_context = nil
140
+ @instance = nil
141
+ @state = :failed
142
+ @last_error = error
143
+ ctx&.dispose
144
+ end
133
145
  end
134
146
 
135
147
  # Backwards-compatibility alias (AGENTS.md terminology). Kept for external
@@ -101,7 +101,11 @@ module Rubik
101
101
  # object is re-provided (identity change), so its new instance is injected.
102
102
  # Both transitions run reconcile_all(changed_service:) OUTSIDE the monitor.
103
103
  def provide(service_name, service)
104
- @monitor.synchronize { @context.provide(service_name, service) }
104
+ @monitor.synchronize do
105
+ raise ContextDisposedError, "Cannot provide service on a disposed Manager" if @disposed
106
+
107
+ @context.provide(service_name, service)
108
+ end
105
109
  # reconcile_all runs OUTSIDE this lock so a failing fiber's backoff sleep
106
110
  # never serializes other threads (Finding 3).
107
111
  reconcile_all(changed_service: service_name)
@@ -198,22 +202,25 @@ module Rubik
198
202
  end
199
203
 
200
204
  def dispose!
205
+ fibers_to_dispose = nil
201
206
  @monitor.synchronize do
202
207
  return if @disposed
203
208
 
204
209
  @disposed = true
205
- begin
206
- @fibers.values.reverse_each do |fiber|
207
- fiber.dispose!
208
- rescue StandardError => e
209
- Rubik::Log.warn(:runtime, "fiber '#{fiber.name}' dispose failed: #{e.class}: #{e.message}")
210
- end
211
- ensure
212
- @fibers.clear
213
- @retry_gate.clear_all # fresh-eye R2: no bookkeeping outlives the manager
214
- @context.dispose
215
- end
210
+ fibers_to_dispose = @fibers.values.reverse
211
+ @fibers.clear
212
+ @retry_gate.clear_all # fresh-eye R2: no bookkeeping outlives the manager
213
+ end
214
+
215
+ # Execute fiber teardown and context disposal OUTSIDE the monitor lock
216
+ # so arbitrary user teardown inverses never serialize manager operations (Finding F4).
217
+ fibers_to_dispose.each do |fiber|
218
+ fiber.dispose!
219
+ rescue StandardError => e
220
+ Rubik::Log.warn(:runtime, "fiber '#{fiber.name}' dispose failed: #{e.class}: #{e.message}")
216
221
  end
222
+
223
+ @context.dispose
217
224
  end
218
225
 
219
226
  private