rubik 0.9.1 → 0.11.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 (138) hide show
  1. checksums.yaml +4 -4
  2. data/ATTRIBUTION.md +1 -1
  3. data/CHANGELOG.md +203 -1
  4. data/lib/rubik/adapter/base.rb +2 -1
  5. data/lib/rubik/adapter/process.rb +28 -67
  6. data/lib/rubik/ast/extractor.rb +2 -1
  7. data/lib/rubik/ast/treesitter_extractor.rb +2 -1
  8. data/lib/rubik/benchmark/vakanuvis_adoption.rb +12 -4
  9. data/lib/rubik/buffer/apply_contract.rb +3 -3
  10. data/lib/rubik/buffer/apply_transaction.rb +165 -0
  11. data/lib/rubik/buffer/manager.rb +26 -120
  12. data/lib/rubik/config/deep_ops.rb +4 -1
  13. data/lib/rubik/config/defaults.rb +6 -3
  14. data/lib/rubik/config/schema.rb +8 -0
  15. data/lib/rubik/config/secret_policy.rb +198 -0
  16. data/lib/rubik/config/store.rb +2 -1
  17. data/lib/rubik/config.rb +13 -2
  18. data/lib/rubik/context/ignore_rules.rb +193 -0
  19. data/lib/rubik/context/scanner.rb +46 -161
  20. data/lib/rubik/diagnostics/collector.rb +0 -9
  21. data/lib/rubik/errors.rb +15 -0
  22. data/lib/rubik/event_bus.rb +2 -1
  23. data/lib/rubik/kernel/dispatcher.rb +12 -7
  24. data/lib/rubik/kernel/unit.rb +4 -1
  25. data/lib/rubik/llm/client.rb +6 -200
  26. data/lib/rubik/llm/connection_pool.rb +104 -0
  27. data/lib/rubik/llm/registry.rb +13 -9
  28. data/lib/rubik/llm/router.rb +2 -5
  29. data/lib/rubik/llm/sse_parser.rb +110 -0
  30. data/lib/rubik/log.rb +21 -0
  31. data/lib/rubik/lsp/circuit_breaker.rb +98 -0
  32. data/lib/rubik/lsp/client.rb +77 -273
  33. data/lib/rubik/lsp/client_provisioner.rb +49 -0
  34. data/lib/rubik/lsp/manager.rb +67 -96
  35. data/lib/rubik/lsp/transport.rb +365 -0
  36. data/lib/rubik/mcp/boot_lifecycle.rb +6 -2
  37. data/lib/rubik/mcp/boot_run.rb +190 -0
  38. data/lib/rubik/mcp/manager.rb +55 -166
  39. data/lib/rubik/mcp/transport/stdio.rb +4 -1
  40. data/lib/rubik/orchestrator/auto_apply.rb +8 -6
  41. data/lib/rubik/orchestrator/continuation_manager.rb +3 -22
  42. data/lib/rubik/orchestrator/goal_ledger/ledger.rb +12 -1
  43. data/lib/rubik/orchestrator/goal_ledger/schema_vocabulary.rb +38 -0
  44. data/lib/rubik/orchestrator/goal_ledger/xml_render.rb +6 -1
  45. data/lib/rubik/orchestrator/goal_ledger.rb +1 -0
  46. data/lib/rubik/orchestrator/goal_session.rb +53 -39
  47. data/lib/rubik/orchestrator/loop.rb +28 -47
  48. data/lib/rubik/orchestrator/lsp_feedback.rb +1 -1
  49. data/lib/rubik/orchestrator/maestro_gate.rb +5 -7
  50. data/lib/rubik/orchestrator/provider_recovery.rb +4 -2
  51. data/lib/rubik/orchestrator/provider_resolver.rb +4 -2
  52. data/lib/rubik/orchestrator/resume_window.rb +96 -0
  53. data/lib/rubik/orchestrator/shell_deps.rb +16 -0
  54. data/lib/rubik/orchestrator/step_executor.rb +2 -1
  55. data/lib/rubik/orchestrator/stream_manager.rb +2 -1
  56. data/lib/rubik/orchestrator/subagent/deferred_spec.rb +4 -1
  57. data/lib/rubik/orchestrator/subagent/instance.rb +7 -12
  58. data/lib/rubik/orchestrator/subagent/lifecycle.rb +3 -1
  59. data/lib/rubik/orchestrator/subagent/notices.rb +2 -2
  60. data/lib/rubik/orchestrator/subagent/questioner.rb +3 -1
  61. data/lib/rubik/orchestrator/subagent/reaper.rb +3 -5
  62. data/lib/rubik/orchestrator/subagent/resilience.rb +4 -2
  63. data/lib/rubik/orchestrator/subagent/result_archive.rb +0 -4
  64. data/lib/rubik/orchestrator/subagent/run_cycle.rb +2 -7
  65. data/lib/rubik/orchestrator/subagent/spawn_transaction.rb +11 -2
  66. data/lib/rubik/orchestrator/subagent/step_runner.rb +10 -2
  67. data/lib/rubik/orchestrator/subagent/transcript_formatter.rb +2 -1
  68. data/lib/rubik/orchestrator/subagent/type_definition.rb +0 -4
  69. data/lib/rubik/orchestrator/tool_timeout.rb +121 -1
  70. data/lib/rubik/platform/io_drain.rb +5 -2
  71. data/lib/rubik/platform/process.rb +144 -54
  72. data/lib/rubik/platform.rb +2 -1
  73. data/lib/rubik/plugin/manager.rb +2 -1
  74. data/lib/rubik/plugin/storage.rb +8 -8
  75. data/lib/rubik/repl/commands/agent_context.rb +8 -7
  76. data/lib/rubik/repl/commands/agent_execution.rb +13 -32
  77. data/lib/rubik/repl/commands/agent_models.rb +4 -3
  78. data/lib/rubik/repl/commands/agent_providers.rb +43 -2
  79. data/lib/rubik/repl/commands/base.rb +47 -2
  80. data/lib/rubik/repl/commands/buffer.rb +5 -4
  81. data/lib/rubik/repl/commands/lsp.rb +2 -1
  82. data/lib/rubik/repl/commands/pruner.rb +2 -1
  83. data/lib/rubik/repl/commands/secrets.rb +151 -0
  84. data/lib/rubik/repl/commands/workspace.rb +60 -150
  85. data/lib/rubik/repl/commands/workspace_approval.rb +209 -0
  86. data/lib/rubik/repl/config_wiring.rb +8 -6
  87. data/lib/rubik/repl/hooks.rb +2 -1
  88. data/lib/rubik/repl/input_execution.rb +162 -79
  89. data/lib/rubik/repl/input_loop.rb +2 -1
  90. data/lib/rubik/repl/lifecycle.rb +60 -210
  91. data/lib/rubik/repl/notice_router.rb +319 -0
  92. data/lib/rubik/repl/paste_support.rb +3 -1
  93. data/lib/rubik/repl/presentation.rb +5 -3
  94. data/lib/rubik/repl/pruner/gate.rb +3 -1
  95. data/lib/rubik/repl/pruner/harness.rb +2 -1
  96. data/lib/rubik/repl/shell.rb +4 -3
  97. data/lib/rubik/repl/tee_io.rb +2 -1
  98. data/lib/rubik/repl/turn_recorder.rb +6 -5
  99. data/lib/rubik/runtime/ast_service.rb +2 -1
  100. data/lib/rubik/runtime/discovery.rb +3 -2
  101. data/lib/rubik/runtime/loop_service.rb +4 -3
  102. data/lib/rubik/runtime/manifest_store.rb +9 -1
  103. data/lib/rubik/runtime/overlay_guard.rb +127 -0
  104. data/lib/rubik/runtime/overlay_storage.rb +109 -163
  105. data/lib/rubik/runtime/task_manager.rb +64 -25
  106. data/lib/rubik/sandbox/driver/docker.rb +5 -1
  107. data/lib/rubik/sandbox/runner.rb +21 -19
  108. data/lib/rubik/security/audit_log.rb +2 -1
  109. data/lib/rubik/security/command_gate.rb +126 -243
  110. data/lib/rubik/security/guard.rb +7 -3
  111. data/lib/rubik/security/secret_store.rb +492 -0
  112. data/lib/rubik/security/segment_report.rb +161 -0
  113. data/lib/rubik/security/synthesis_gate.rb +8 -11
  114. data/lib/rubik/session/manager.rb +7 -1
  115. data/lib/rubik/session/recorder.rb +2 -1
  116. data/lib/rubik/skills/manager.rb +4 -4
  117. data/lib/rubik/storage/search.rb +49 -0
  118. data/lib/rubik/storage/store.rb +13 -20
  119. data/lib/rubik/storage/transcript_indexer.rb +3 -2
  120. data/lib/rubik/storage/vakanuvis/harness.rb +2 -3
  121. data/lib/rubik/storage/vakanuvis.rb +2 -1
  122. data/lib/rubik/tools/base.rb +22 -0
  123. data/lib/rubik/tools/builtins/files.rb +3 -15
  124. data/lib/rubik/tools/builtins/goal_ledger.rb +12 -1
  125. data/lib/rubik/tools/builtins/grep.rb +1 -6
  126. data/lib/rubik/tools/builtins/lifecycle.rb +6 -5
  127. data/lib/rubik/tools/builtins/synthesis.rb +3 -3
  128. data/lib/rubik/tools/lifecycle_rollbacks.rb +14 -1
  129. data/lib/rubik/tools/preflight_runner.rb +2 -1
  130. data/lib/rubik/tools/truncator.rb +48 -36
  131. data/lib/rubik/tools/uri_resolver.rb +3 -2
  132. data/lib/rubik/ui/banner.rb +4 -3
  133. data/lib/rubik/ui/capability.rb +1 -0
  134. data/lib/rubik/ui/spinner.rb +3 -1
  135. data/lib/rubik/ui/statusline.rb +6 -5
  136. data/lib/rubik/version.rb +1 -1
  137. data/lib/rubik.rb +4 -5
  138. metadata +20 -1
@@ -0,0 +1,209 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../../storage/layout"
4
+
5
+ module Rubik
6
+ module REPL
7
+ module Commands
8
+ # Value object resolving one workspace/directory approval request:
9
+ # (path, read-write mode, persistence scope, trust). All collaborators
10
+ # (config, buffer manager, sandbox runner, security guard, output
11
+ # stream) are injected explicitly — no ambient globals (AGENTS.md §5).
12
+ #
13
+ # The REPL command handlers stay thin adapters: they parse the raw
14
+ # argv into these attributes, print usage lines, and delegate the
15
+ # trust check, the runtime mutation and the config persistence here.
16
+ # Every message spelling is pinned to what the handlers used to emit.
17
+ class WorkspaceApproval
18
+ attr_reader :path, :rw, :scope
19
+
20
+ def initialize(path:, read_write:, scope:, config:, buffer_manager:, out:, guard:, sandbox_runner: nil,
21
+ index_sync: nil, effective_root: nil)
22
+ @path = path
23
+ @rw = read_write
24
+ @scope = scope
25
+ @config = config
26
+ @buffer_manager = buffer_manager
27
+ @out = out
28
+ @guard = guard
29
+ @sandbox_runner = sandbox_runner
30
+ @index_sync = index_sync
31
+ @effective_root = effective_root
32
+ end
33
+
34
+ # Trust resolution (fail-closed): a dangerous system root is refused
35
+ # with the pinned "Security Error:" line before any mutation runs.
36
+ def trusted?
37
+ @guard.verify_root_safety!(@path)
38
+ true
39
+ rescue Rubik::Security::BlockedWriteError => e
40
+ @out.puts "Security Error: #{e.message}"
41
+ false
42
+ end
43
+
44
+ # !workspace add <path> [--rw]: register an additional workspace root
45
+ # on the buffer manager, optionally re-index coeffects, and persist.
46
+ def add_root!
47
+ expanded = @buffer_manager.add_root(@path, rw: @rw)
48
+
49
+ sync_index_if_enabled!
50
+
51
+ current_roots = Array(Rubik::Storage::Layout.config_get(@config, "workspace.additional_roots", [])).dup
52
+ current_roots << @path unless current_roots.include?(@path)
53
+ res = @config.set("workspace.additional_roots", current_roots, persist: @scope)
54
+ return if Base.report_persist_failure(@out, res, @scope)
55
+
56
+ mode_str = @rw ? "Read-Write" : "Read-Only"
57
+ @out.puts "[Rubik::Workspace] Added additional root: #{expanded} (Mode: #{mode_str}) " \
58
+ "[#{Base.scope_label(@scope)}]."
59
+ end
60
+
61
+ # !workspace allow / !allow-dir add <path> [--rw|--ro]: allow an
62
+ # external directory for Buffer I/O and Sandbox (Zero-AST: no index
63
+ # sync) and persist.
64
+ def allow_dir!
65
+ expanded = @buffer_manager.add_allowed_dir(@path, rw: @rw)
66
+ @sandbox_runner&.add_allowed_dir(@path)
67
+
68
+ current_dirs = Array(Rubik::Storage::Layout.config_get(@config, "workspace.allowed_external_dirs", [])).dup
69
+ current_dirs << @path unless current_dirs.include?(@path)
70
+ res = @config.set("workspace.allowed_external_dirs", current_dirs, persist: @scope)
71
+ return if Base.report_persist_failure(@out, res, @scope)
72
+
73
+ mode_str = @rw ? "Read-Write" : "Read-Only"
74
+ @out.puts "[Rubik::Allow] Added allowed external directory: #{expanded} (Mode: #{mode_str}) " \
75
+ "[#{Base.scope_label(@scope)}]."
76
+ end
77
+
78
+ # !workspace remove <path>: unregister an additional root, re-index,
79
+ # and prune persisted entries (matched by resolved path or raw arg).
80
+ def remove_root!
81
+ expanded = @buffer_manager.remove_root(@path)
82
+
83
+ sync_index_if_enabled!
84
+
85
+ current_roots = Array(Rubik::Storage::Layout.config_get(@config, "workspace.additional_roots", [])).dup
86
+ current_roots.reject! { |r| File.expand_path(r, @effective_root) == expanded || r == @path }
87
+ res = @config.set("workspace.additional_roots", current_roots, persist: @scope)
88
+ return if Base.report_persist_failure(@out, res, @scope)
89
+
90
+ @out.puts "[Rubik::Workspace] Removed additional root: #{expanded} [#{Base.scope_label(@scope)}]."
91
+ end
92
+
93
+ # !allow-dir remove <path>: retract an allowed external directory
94
+ # from Buffer and Sandbox, then prune persisted entries.
95
+ def remove_allowed_dir!
96
+ expanded = @buffer_manager&.remove_allowed_dir(@path)
97
+ @sandbox_runner&.remove_allowed_dir(@path)
98
+
99
+ current_dirs = Array(Rubik::Storage::Layout.config_get(@config, "workspace.allowed_external_dirs", [])).dup
100
+ current_dirs.reject! { |d| File.expand_path(d, @effective_root) == expanded || d == @path }
101
+ res = @config.set("workspace.allowed_external_dirs", current_dirs, persist: @scope)
102
+ return if Base.report_persist_failure(@out, res, @scope)
103
+
104
+ @out.puts "[Rubik::Allow] Removed allowed external directory: #{expanded} [#{Base.scope_label(@scope)}]."
105
+ end
106
+
107
+ private
108
+
109
+ # Sync context index & AST coeffects when auto-indexing is on
110
+ # (workspace.auto_index_additional, default true).
111
+ def sync_index_if_enabled!
112
+ auto_idx = Rubik::Storage::Layout.config_get(@config, "workspace.auto_index_additional", true)
113
+ @index_sync&.call if auto_idx
114
+ end
115
+ end
116
+
117
+ # Value object for one operator command-prefix allowlist mutation
118
+ # (!allow-cmd add|remove). Wraps the fail-closed broad-token RCE gate,
119
+ # the catastrophic-pattern veto, duplicate handling and persistence
120
+ # with the exact messages the inline handlers used to emit.
121
+ class CommandPrefixApproval
122
+ def initialize(config:, out:, guard:, classifier: Rubik::Security::Classifier)
123
+ @config = config
124
+ @out = out
125
+ @guard = guard
126
+ @classifier = classifier
127
+ end
128
+
129
+ def add(tokens_to_add, scope)
130
+ entry_tokens = tokens_to_add.reject { |a| a == "--force" }
131
+ entry = entry_tokens.join(" ").strip
132
+ if entry.empty?
133
+ @out.puts 'Usage: !allow-cmd add "<command prefix>" [--project|--global] [--force]'
134
+ return
135
+ end
136
+
137
+ return if broad_token_blocked?(entry)
138
+
139
+ return if catastrophic_pattern_blocked?(entry)
140
+
141
+ current = Array(Rubik::Storage::Layout.config_get(@config, "security.command_allowlist", [])).dup
142
+ if current.include?(entry)
143
+ @out.puts "[Rubik::AllowCmd] '#{entry}' is already allowlisted."
144
+ return
145
+ end
146
+ current << entry
147
+ res = @config.set("security.command_allowlist", current, persist: scope)
148
+ @guard&.log_audit("allowlist_add", command: entry, scope: scope)
149
+ return if Base.report_persist_failure(@out, res, scope)
150
+
151
+ @out.puts "[Rubik::AllowCmd] Added command prefix: #{entry} [#{Base.scope_label(scope)}]."
152
+ end
153
+
154
+ def remove(entry, scope)
155
+ current = Array(Rubik::Storage::Layout.config_get(@config, "security.command_allowlist", [])).dup
156
+ unless current.include?(entry)
157
+ @out.puts "[Rubik::AllowCmd] '#{entry}' is not in the allowlist."
158
+ return
159
+ end
160
+ current.delete(entry)
161
+ res = @config.set("security.command_allowlist", current, persist: scope)
162
+ @guard&.log_audit("allowlist_remove", command: entry, scope: scope)
163
+ return if Base.report_persist_failure(@out, res, scope)
164
+
165
+ @out.puts "[Rubik::AllowCmd] Removed command prefix: #{entry} [#{Base.scope_label(scope)}]."
166
+ end
167
+
168
+ private
169
+
170
+ # Fail closed (G3 triage, Priority-1 site): a classifier crash must
171
+ # not silently skip the broad-token RCE check — treat the token as
172
+ # broad and let the operator pass a narrow prefix.
173
+ def broad_token_blocked?(entry)
174
+ tokens = entry.split(/\s+/)
175
+ broad = begin
176
+ base = @classifier.classify(tokens.first)
177
+ base.classification == :dangerous && tokens.size == 1
178
+ rescue StandardError => e
179
+ Rubik::Log.warn(:security, "classifier failed for '#{tokens.first}' (#{e.class}: #{e.message}); treating as broad")
180
+ true
181
+ end
182
+
183
+ # Fail-closed against unbounded execution: a broad, single-token
184
+ # dangerous entry (e.g. "node", "python", "bash") grants command
185
+ # execution for EVERY invocation of that binary, so `node` →
186
+ # `node -e 'malicious()'` RCE. Such broad tokens are blocked with
187
+ # or without --force — the operator should use a narrow prefix.
188
+ return false unless broad
189
+
190
+ @out.puts "Blocked: '#{entry}' is a broad, single-token dangerous command. Even with --force it grants " \
191
+ "unbounded command execution (e.g. `#{tokens.first} -e 'malicious(...)'` RCE). " \
192
+ "Use a narrow prefix instead (e.g. \"#{tokens.first} <script>\")."
193
+ true
194
+ end
195
+
196
+ # The catastrophic destructive-pattern fallback always runs: a
197
+ # dangerous multi-token entry may never add `rm -rf /`-style chains
198
+ # to the allowlist, with or without --force.
199
+ def catastrophic_pattern_blocked?(entry)
200
+ @guard.verify_command_fallback_regex!(entry)
201
+ false
202
+ rescue Rubik::Security::BlockedWriteError => e
203
+ @out.puts "Blocked: '#{entry}' matches a catastrophic destructive pattern and cannot be allowlisted: #{e.message}"
204
+ true
205
+ end
206
+ end
207
+ end
208
+ end
209
+ end
@@ -1,5 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "../log"
4
+
3
5
  module Rubik
4
6
  module REPL
5
7
  # Wires reactive configuration observers to Shell subsystems.
@@ -60,7 +62,7 @@ module Rubik
60
62
  # only, so the mirror pushed writes into a key nothing reads back.
61
63
  # The incantation stays accepted; it warns instead of mirroring.
62
64
  cleanups << config.on_change("network.allow") do |_key, _val, _old|
63
- warn "[ConfigWiring] [DEPRECATION] Config key 'network.allow' is deprecated and has no effect. Use 'sandbox.allow_network' instead."
65
+ Rubik::Log.warn(:config, "[ConfigWiring] [DEPRECATION] Config key 'network.allow' is deprecated and has no effect. Use 'sandbox.allow_network' instead.")
64
66
  end
65
67
 
66
68
  cleanups
@@ -83,7 +85,7 @@ module Rubik
83
85
  begin
84
86
  shell.guard.verify_root_safety!(r)
85
87
  rescue Rubik::Security::BlockedWriteError => e
86
- warn "[ConfigWiring] #{e.message}. Skipping additional root #{r}."
88
+ Rubik::Log.warn(:config, "[ConfigWiring] #{e.message}. Skipping additional root #{r}.")
87
89
  next
88
90
  end
89
91
  end
@@ -92,7 +94,7 @@ module Rubik
92
94
  removed_roots.each { |r| shell.buffer_manager&.remove_root(r) }
93
95
 
94
96
  if (new_roots.any? || removed_roots.any?) &&
95
- shell.config.fetch("workspace.auto_index_additional", true) && shell.context_index
97
+ Rubik::Storage::Layout.config_get(shell.config, "workspace.auto_index_additional", true) && shell.context_index
96
98
  shell.context_index.additional_roots = shell.buffer_manager&.additional_roots
97
99
  shell.context_index.full_scan
98
100
  shell.warm_ast_graph(async: false) if shell.respond_to?(:warm_ast_graph)
@@ -110,7 +112,7 @@ module Rubik
110
112
  begin
111
113
  shell.guard.verify_root_safety!(d)
112
114
  rescue Rubik::Security::BlockedWriteError => e
113
- warn "[ConfigWiring] #{e.message}. Skipping allowed directory #{d}."
115
+ Rubik::Log.warn(:config, "[ConfigWiring] #{e.message}. Skipping allowed directory #{d}.")
114
116
  next
115
117
  end
116
118
  end
@@ -130,8 +132,8 @@ module Rubik
130
132
  return unless ["context.include", "context.exclude"].include?(key)
131
133
  return unless shell.context_index.respond_to?(:update_file_filters)
132
134
 
133
- inc = shell.config.fetch("context.include", [])
134
- exc = shell.config.fetch("context.exclude", [])
135
+ inc = Rubik::Storage::Layout.config_get(shell.config, "context.include", [])
136
+ exc = Rubik::Storage::Layout.config_get(shell.config, "context.exclude", [])
135
137
  shell.context_index.update_file_filters(includes: inc, excludes: exc)
136
138
  shell.warm_ast_graph(async: false) if shell.respond_to?(:warm_ast_graph)
137
139
  end
@@ -1,13 +1,14 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "logger"
4
+ require_relative "../log"
4
5
 
5
6
  module Rubik
6
7
  module REPL
7
8
  class Hooks
8
9
  KNOWN_EVENTS = [:file_changed, :test_failed, :before_command, :after_command].freeze
9
10
 
10
- def initialize(logger: Logger.new($stderr))
11
+ def initialize(logger: Rubik::Log.forwarder(:repl_hooks))
11
12
  @hooks = Hash.new { |h, k| h[k] = [] }
12
13
  @logger = logger
13
14
  @mutex = Mutex.new
@@ -1,7 +1,9 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "stringio"
4
+ require_relative "../log"
4
5
  require_relative "tee_io"
6
+ require_relative "../storage/layout"
5
7
 
6
8
  module Rubik
7
9
  module REPL
@@ -82,7 +84,7 @@ module Rubik
82
84
  clean_raw = Rubik::Security::Redactor.redact(parsed.raw)
83
85
  @recorder&.record_repl_command(clean_raw, output_text)
84
86
  # Plan 61 D-8: bound what a bang command leaves in LLM memory; the recorder keeps the full text.
85
- max_chars = @config.fetch("tools.max_output_chars", Rubik::Tools::Truncator::DEFAULT_MAX_CHARS)
87
+ max_chars = Rubik::Storage::Layout.config_get(@config, "tools.max_output_chars", Rubik::Tools::Truncator::DEFAULT_MAX_CHARS)
86
88
  # Deliberately context-scoped (issue #349 F8): truncation_strategy is a
87
89
  # tool-output contract (the two orchestrator planes); bang-command echo
88
90
  # is REPL history capture and stays head_tail, outside the knob's promise.
@@ -144,6 +146,14 @@ module Rubik
144
146
  true
145
147
  end
146
148
 
149
+ # Named phases of the free-text turn (issue #445): execute_free_text is
150
+ # the orchestrator — arming → routing → display/loop assembly → run →
151
+ # settle, with the rescue ladder and ensure teardown delegated to their
152
+ # own helpers below. All helpers run on the Shell (self stays the shell,
153
+ # so @output/@recorder reads are unchanged); every piece of state that
154
+ # was a local of the old monolith (task, renderer, md_stream, theme,
155
+ # md_enabled, orchestrator, interrupted) reaches its consumer explicitly
156
+ # as a parameter — nothing is passed through self or ambient state.
147
157
  def execute_free_text(text)
148
158
  # Wakeloop fix 2026-10-09: ^C settles the wake debt instead of
149
159
  # letting the interrupted turn's own ensure re-arm the cycle. Bound
@@ -152,10 +162,45 @@ module Rubik
152
162
  # an unbound read would mask the in-flight exception with a
153
163
  # NameError, breaking the "cleanup must never mask" contract.
154
164
  interrupted = false
155
- # Task ownership (issue #125): this turn owns the subagents it spawns.
156
- # The token is published for the turn's duration; ^C cancels it and the
157
- # supervisor stops exactly the owned descendants (detached work and
158
- # older turns' executions carry different tokens and survive).
165
+ task = start_free_text_turn!(text)
166
+ renderer = md_stream = orchestrator = nil
167
+ routed = route_free_text!(text)
168
+ return if routed.nil?
169
+
170
+ @runtime_manager.provide(:llm_client, routed[:provider])
171
+
172
+ # Pruner apply seam (context-pruner 2026-10-09): budayıcı bir plan
173
+ # aşamaladıysa pencereyi turn tohumlanmadan ÖNCE takas et (knob
174
+ # kapalıysa no-op; !plan'ın execute_free_text devri ve otonom notice
175
+ # turn'leri buradan geçer).
176
+ apply_staged_prune_plan!
177
+
178
+ max_steps = Rubik::Storage::Layout.config_get(@config, "agent.max_steps", 40).to_i
179
+ warn_ratio = Rubik::Storage::Layout.config_get(@config, "agent.warn_at_ratio", 0.75).to_f
180
+ theme = self.theme
181
+ renderer, md_stream, md_enabled = build_turn_display(theme, max_steps)
182
+ orchestrator = build_turn_orchestrator(routed, max_steps, warn_ratio, renderer, md_stream)
183
+
184
+ res = run_free_text_loop(orchestrator, text)
185
+ settle_free_text_result!(text, res, orchestrator: orchestrator, theme: theme, md_enabled: md_enabled)
186
+ rescue Interrupt
187
+ interrupted = true
188
+ handle_interrupted_free_text!(text, task, orchestrator)
189
+ rescue Rubik::LLM::ClientError => e
190
+ handle_llm_client_error!(text, e, orchestrator)
191
+ rescue StandardError => e
192
+ handle_unexpected_error!(text, e, orchestrator)
193
+ ensure
194
+ teardown_free_text_turn!(interrupted, orchestrator, renderer, md_stream)
195
+ end
196
+
197
+ # Arming phase: publishes the turn's task-cancellation token (issue #125
198
+ # — the turn owns the subagents it spawns; ^C cancels it and the
199
+ # supervisor stops exactly the owned descendants; detached work and
200
+ # older turns' executions carry different tokens and survive), settles
201
+ # the wake debt and records the turn's entry events. Returns the token
202
+ # for the rescue ladder.
203
+ def start_free_text_turn!(text)
159
204
  task = Rubik::Orchestrator::TaskCancellation.new
160
205
  @active_task = task
161
206
  @runtime_manager&.provide(Rubik::Coeffects::TASK_CANCELLATION, task)
@@ -165,73 +210,90 @@ module Rubik
165
210
  clear_pending_wake_notices! if respond_to?(:clear_pending_wake_notices!)
166
211
  @recorder&.record_user_turn(text)
167
212
  @event_bus.emit(:prompt_received, prompt: text)
213
+ task
214
+ end
168
215
 
169
- renderer = md_stream = orchestrator = nil
216
+ # Routing phase: resolves the turn route; when no LLM provider is
217
+ # available, reports the failure (message + failed-turn record) and
218
+ # returns nil so the caller aborts the turn — ensure still unwinds.
219
+ def route_free_text!(text)
170
220
  routed = resolve_turn_route(text)
171
- provider = routed[:provider]
172
-
173
- if provider.nil?
174
- spec_str = routed[:spec].is_a?(Hash) ? "#{routed[:spec]['provider']}/#{routed[:spec]['name']}" : routed[:spec].to_s
175
- @output.puts "Hata: Model sağlayıcısı başlatılamadı (#{spec_str})."
176
- record_failed_turn!(text, "failed", "no LLM provider available (#{spec_str})", nil)
177
- return
178
- end
221
+ return routed if routed[:provider]
179
222
 
180
- @runtime_manager.provide(:llm_client, provider)
181
-
182
- # Pruner apply seam (context-pruner 2026-10-09): budayıcı bir plan
183
- # aşamaladıysa pencereyi turn tohumlanmadan ÖNCE takas et (knob
184
- # kapalıysa no-op; !plan'ın execute_free_text devri ve otonom notice
185
- # turn'leri buradan geçer).
186
- apply_staged_prune_plan!
223
+ spec_str = routed[:spec].is_a?(Hash) ? "#{routed[:spec]['provider']}/#{routed[:spec]['name']}" : routed[:spec].to_s
224
+ @output.puts "Hata: Model sağlayıcısı başlatılamadı (#{spec_str})."
225
+ record_failed_turn!(text, "failed", "no LLM provider available (#{spec_str})", nil)
226
+ nil
227
+ end
187
228
 
188
- max_steps = @config.fetch("agent.max_steps", 40).to_i
189
- warn_ratio = @config.fetch("agent.warn_at_ratio", 0.75).to_f
190
- theme = self.theme
229
+ # Display phase: builds the step renderer and the live markdown stream.
230
+ # Returns [renderer, md_stream, md_enabled]; md_enabled flows to the
231
+ # batch-render path in settle_free_text_result!.
232
+ def build_turn_display(theme, max_steps)
191
233
  renderer = @ui_renderer || Rubik::UI::Renderer.new(config: @config, max_steps: max_steps, output: @output, theme: theme)
192
- md_enabled = @config.fetch("ui.markdown", "live") != "off"
234
+ md_enabled = Rubik::Storage::Layout.config_get(@config, "ui.markdown", "live") != "off"
193
235
  md_stream = Rubik::UI::MarkdownStream.new(theme, enabled: md_enabled)
236
+ [renderer, md_stream, md_enabled]
237
+ end
194
238
 
195
- orchestrator = orchestrator_loop(
196
- provider: provider,
239
+ # Loop-assembly phase: builds the orchestrator loop with the turn's
240
+ # step handler wired to the turn's renderer and markdown stream.
241
+ def build_turn_orchestrator(routed, max_steps, warn_ratio, renderer, md_stream)
242
+ orchestrator_loop(
243
+ provider: routed[:provider],
197
244
  model: routed[:model],
198
245
  max_steps: max_steps,
199
246
  warn_at_ratio: warn_ratio,
200
247
  context_limit: routed[:context_limit],
201
248
  max_output_tokens: routed[:max_output_tokens],
202
- on_step: lambda { |step_info|
203
- case step_info[:type]&.to_sym
204
- when :chunk
205
- renderer.render(step_info) # stops spinner before raw output
206
- md_stream.push(step_info[:delta]) { |seg| @output.print seg }
207
- @output.flush if @output.respond_to?(:flush)
208
- when :chunk_end
209
- renderer.render(step_info)
210
- md_stream.finish { |seg| @output.print seg }
211
- @output.flush if @output.respond_to?(:flush)
212
- when :tool_call
213
- @recorder&.record_tool_call(step_info[:tool], step_info[:args], call_id: step_info[:call_id])
214
- formatted = renderer.render(step_info)
215
- @output.puts formatted if formatted && !formatted.empty?
216
- @output.flush if @output.respond_to?(:flush)
217
- when :tool_result
218
- @recorder&.record_tool_result(step_info[:tool], step_info[:output], status: step_info[:status] || :ok, call_id: step_info[:call_id])
219
- formatted = renderer.render(step_info)
220
- @output.puts formatted if formatted && !formatted.empty?
249
+ on_step: turn_step_handler(renderer, md_stream)
250
+ )
251
+ end
252
+
253
+ # The per-step streaming policy for free-text turns. The lambda closes
254
+ # over renderer/md_stream (passed explicitly) and the Shell's live
255
+ # @output/@recorder — self at invocation time is still the Shell, the
256
+ # same closure the inline version had.
257
+ def turn_step_handler(renderer, md_stream)
258
+ lambda { |step_info|
259
+ case step_info[:type]&.to_sym
260
+ when :chunk
261
+ renderer.render(step_info) # stops spinner before raw output
262
+ md_stream.push(step_info[:delta]) { |seg| @output.print seg }
263
+ @output.flush if @output.respond_to?(:flush)
264
+ when :chunk_end
265
+ renderer.render(step_info)
266
+ md_stream.finish { |seg| @output.print seg }
267
+ @output.flush if @output.respond_to?(:flush)
268
+ when :tool_call
269
+ @recorder&.record_tool_call(step_info[:tool], step_info[:args], call_id: step_info[:call_id])
270
+ formatted = renderer.render(step_info)
271
+ @output.puts formatted if formatted && !formatted.empty?
272
+ @output.flush if @output.respond_to?(:flush)
273
+ when :tool_result
274
+ @recorder&.record_tool_result(step_info[:tool], step_info[:output], status: step_info[:status] || :ok, call_id: step_info[:call_id])
275
+ formatted = renderer.render(step_info)
276
+ @output.puts formatted if formatted && !formatted.empty?
277
+ @output.flush if @output.respond_to?(:flush)
278
+ else
279
+ formatted = renderer.render(step_info)
280
+ if formatted && !formatted.empty?
281
+ @output.puts formatted
221
282
  @output.flush if @output.respond_to?(:flush)
222
- else
223
- formatted = renderer.render(step_info)
224
- if formatted && !formatted.empty?
225
- @output.puts formatted
226
- @output.flush if @output.respond_to?(:flush)
227
- end
228
283
  end
229
- }
230
- )
284
+ end
285
+ }
286
+ end
287
+
288
+ # Run phase: publishes @active_loop before the loop starts (the
289
+ # reentrancy guard relied on by execute_subagent_notice_turn! and
290
+ # route_subagent_notice's idle branch) and drives the
291
+ # budget-exhausted continue prompt. Returns the final loop result.
292
+ def run_free_text_loop(orchestrator, text)
231
293
  @active_loop = orchestrator
232
294
  res = orchestrator.run(text, conversation_history: @conversation_history)
233
295
 
234
- while !res[:ok] && res[:reason] == :budget_exhausted && @config.fetch("agent.ask_continue_on_limit", true)
296
+ while !res[:ok] && res[:reason] == :budget_exhausted && Rubik::Storage::Layout.config_get(@config, "agent.ask_continue_on_limit", true)
235
297
  @output.puts "\n⚠️ [Rubik::Agent] #{res[:error]}"
236
298
  ans = ask_yes_no(" [Rubik::Agent] +20 adım ile devam edilsin mi?", default: "n")
237
299
  break unless ["y", "yes", "evet"].include?(ans)
@@ -240,14 +302,20 @@ module Rubik
240
302
  res = orchestrator.continue_loop(20)
241
303
 
242
304
  end
305
+ res
306
+ end
243
307
 
308
+ # Settle phase: merges the turn's tool history, then records and
309
+ # reports the outcome (success render / incomplete report). theme and
310
+ # md_enabled arrive from the display phase for the batch render.
311
+ def settle_free_text_result!(text, res, orchestrator:, theme:, md_enabled:)
244
312
  # Plan 85 D-7 (kök neden): turn içi @history'deki tool ara adımlarını
245
313
  # conversation_history'ye kopyala — böylece continue'da model turn sırasındaki
246
314
  # bağlamı görür ve "sıfırdan keşfe" başlamaz. res[:loop_instance].history,
247
315
  # turn_result'ın döndürdüğü Loop örneğinin @history'sidir.
248
316
  merge_turn_tool_history!(
249
317
  res[:loop_instance]&.history,
250
- max_entries: @config.fetch("context.merge_turn_tool_max_entries", 20).to_i
318
+ max_entries: Rubik::Storage::Layout.config_get(@config, "context.merge_turn_tool_max_entries", 20).to_i
251
319
  )
252
320
 
253
321
  if res[:ok]
@@ -275,11 +343,14 @@ module Rubik
275
343
  @output.puts "Görev tamamlanamadı: #{res[:error]}"
276
344
  record_failed_turn!(text, "incomplete", res[:error], orchestrator)
277
345
  end
278
- rescue Interrupt
279
- interrupted = true
280
- # The user cancelled: queued wake debts settle here. Each queued
281
- # notice already lives in @conversation_history (idle path injects
282
- # at route time), so draining loses nothing the model needed.
346
+ end
347
+
348
+ # Interrupt rescue body: the user cancelled — queued wake debts settle
349
+ # here. Each queued notice already lives in @conversation_history (idle
350
+ # path injects at route time), so draining loses nothing the model
351
+ # needed. `interrupted = true` stays in the orchestrator so the ensure
352
+ # reads the flag before this runs.
353
+ def handle_interrupted_free_text!(text, task, orchestrator)
283
354
  clear_pending_wake_notices! if respond_to?(:clear_pending_wake_notices!)
284
355
  Rubik::REPL::InterruptHandler.restore_console_after_interrupt
285
356
  # Propagate the cancellation to owned work (issue #125) and report the
@@ -294,29 +365,41 @@ module Rubik
294
365
  "reason" => "Interrupted by user (^C)")
295
366
  @output.puts "\n⚠️ [Rubik::Agent] Görev kullanıcı tarafından iptal edildi (^C)."
296
367
  record_failed_turn!(text, "cancelled", "Interrupted by user (^C)", orchestrator)
297
- rescue Rubik::LLM::ClientError => e
298
- # e.message may carry binary bytes (raw HTTP error bodies). Printing
299
- # or recording those would raise INSIDE this rescue clause, bypassing
300
- # every sibling handler and surfacing as a bare
301
- # Encoding::CompatibilityError at the REPL prompt instead of the real
302
- # LLM error. Sanitize before use.
303
- message = Rubik::Platform.safe_utf8(e.message)
368
+ end
369
+
370
+ # LLM::ClientError rescue body. e.message may carry binary bytes (raw
371
+ # HTTP error bodies). Printing or recording those would raise INSIDE the
372
+ # rescue clause, bypassing every sibling handler and surfacing as a bare
373
+ # Encoding::CompatibilityError at the REPL prompt instead of the real
374
+ # LLM error. Sanitize before use.
375
+ def handle_llm_client_error!(text, error, orchestrator)
376
+ message = Rubik::Platform.safe_utf8(error.message)
304
377
  @output.puts "[Rubik::LLM Hatası] #{message}"
305
378
  record_failed_turn!(text, "failed", message, orchestrator)
306
- rescue StandardError => e
307
- message = Rubik::Platform.safe_utf8(e.message)
308
- @output.puts "[Hata] #{e.class}: #{message}"
309
- record_failed_turn!(text, "failed", "#{e.class}: #{message}", orchestrator)
310
- ensure
379
+ end
380
+
381
+ # StandardError rescue body: same binary-byte sanitization as the LLM
382
+ # error path above.
383
+ def handle_unexpected_error!(text, error, orchestrator)
384
+ message = Rubik::Platform.safe_utf8(error.message)
385
+ @output.puts "[Hata] #{error.class}: #{message}"
386
+ record_failed_turn!(text, "failed", "#{error.class}: #{message}", orchestrator)
387
+ end
388
+
389
+ # Ensure-phase teardown. Cleanup must never mask the in-flight exception
390
+ # (Interrupt, LLM error): each step reports its own failure to stderr
391
+ # instead of raising. `interrupted` is the orchestrator's local, passed
392
+ # explicitly (Wakeloop fix 2026-10-09: an interrupted turn must not
393
+ # re-arm the wake cycle).
394
+ def teardown_free_text_turn!(interrupted, orchestrator, renderer, md_stream)
311
395
  @active_loop = nil
312
396
  @active_task = nil
313
397
  # Flush a half-streamed markdown tail so an interrupt never eats the last
314
- # line. Cleanup must never mask the in-flight exception (Interrupt, LLM
315
- # error): each step reports its own failure to stderr instead of raising.
398
+ # line.
316
399
  begin
317
400
  md_stream&.finish { |seg| @output.print seg }
318
401
  rescue StandardError => e
319
- warn "[rubik] markdown tail flush failed: #{e.class}: #{e.message}"
402
+ Rubik::Log.warn(:repl, "[rubik] markdown tail flush failed: #{e.class}: #{e.message}")
320
403
  end
321
404
  kill_spinner!(renderer&.spinner)
322
405
  flush_subagent_notices! if respond_to?(:flush_subagent_notices!)
@@ -343,9 +426,9 @@ module Rubik
343
426
  supervisor = Rubik::Coeffects.get(@runtime_manager&.context, Rubik::Coeffects::SUBAGENT_SUPERVISOR)
344
427
  return nil unless task && supervisor.respond_to?(:cancel_owned)
345
428
 
346
- supervisor.cancel_owned(task, timeout: @config.fetch("subagents.cancel_timeout", 2.0))
429
+ supervisor.cancel_owned(task, timeout: Rubik::Storage::Layout.config_get(@config, "subagents.cancel_timeout", 2.0))
347
430
  rescue StandardError => e
348
- warn "[rubik] task cancellation failed: #{e.class}: #{e.message}"
431
+ Rubik::Log.warn(:repl, "[rubik] task cancellation failed: #{e.class}: #{e.message}")
349
432
  nil
350
433
  end
351
434
 
@@ -373,7 +456,7 @@ module Rubik
373
456
  def kill_spinner!(spinner)
374
457
  spinner&.kill
375
458
  rescue StandardError => e
376
- warn "[rubik] spinner cleanup failed: #{e.class}: #{e.message}"
459
+ Rubik::Log.warn(:repl, "[rubik] spinner cleanup failed: #{e.class}: #{e.message}")
377
460
  end
378
461
 
379
462
  # Command-dispatch spinner cleanup (both branches).
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "prompt_grace"
4
+ require_relative "../storage/layout"
4
5
 
5
6
  module Rubik
6
7
  module REPL
@@ -224,7 +225,7 @@ module Rubik
224
225
  return execute_input(text) unless prompt_grace_interactive?
225
226
 
226
227
  if CommandParser.parse(text).type == :prompt
227
- milliseconds = @config.fetch("ui.prompt_grace_window_ms", 1000)
228
+ milliseconds = Rubik::Storage::Layout.config_get(@config, "ui.prompt_grace_window_ms", 1000)
228
229
  outcome = PromptGrace.new(input: @input, output: @output,
229
230
  context: @runtime_manager&.context).wait(milliseconds)
230
231
  if outcome == :edit