rubik 0.9.0 → 0.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/ATTRIBUTION.md +1 -1
- data/CHANGELOG.md +108 -43
- data/README.md +5 -1
- data/lib/rubik/adapter/base.rb +19 -0
- data/lib/rubik/adapter/generic.rb +0 -14
- data/lib/rubik/adapter/node.rb +2 -0
- data/lib/rubik/ast/treesitter/zig_walker.rb +15 -2
- data/lib/rubik/cli/workspace_trust.rb +16 -0
- data/lib/rubik/config/defaults.rb +23 -0
- data/lib/rubik/config/store.rb +14 -0
- data/lib/rubik/kernel/dispatcher.rb +4 -4
- data/lib/rubik/log.rb +2 -1
- data/lib/rubik/lsp/client.rb +83 -180
- data/lib/rubik/lsp/document_store.rb +209 -0
- data/lib/rubik/mcp/client.rb +4 -3
- data/lib/rubik/mcp/manager.rb +6 -2
- data/lib/rubik/mcp/transport/stdio.rb +51 -9
- data/lib/rubik/orchestrator/goal_session.rb +505 -0
- data/lib/rubik/orchestrator/subagent/instance.rb +4 -0
- data/lib/rubik/orchestrator/subagent/journal.rb +2 -1
- data/lib/rubik/orchestrator/subagent/questioner.rb +21 -6
- data/lib/rubik/orchestrator/subagent/step_runner.rb +1 -1
- data/lib/rubik/orchestrator/subagent/teardown.rb +4 -0
- data/lib/rubik/orchestrator/subagent/transcript_formatter.rb +2 -1
- data/lib/rubik/orchestrator.rb +1 -0
- data/lib/rubik/platform.rb +15 -0
- data/lib/rubik/plugin/storage.rb +20 -29
- data/lib/rubik/repl/commands/agent_context.rb +1 -1
- data/lib/rubik/repl/commands/agent_execution.rb +7 -470
- data/lib/rubik/repl/commands/buffer.rb +1 -1
- data/lib/rubik/repl/commands/lsp.rb +1 -1
- data/lib/rubik/repl/input_loop.rb +1 -1
- data/lib/rubik/repl/lifecycle.rb +28 -0
- data/lib/rubik/runtime/manifest_store.rb +116 -0
- data/lib/rubik/runtime/overlay_storage.rb +247 -196
- data/lib/rubik/runtime/task_manager.rb +7 -2
- data/lib/rubik/runtime.rb +1 -0
- data/lib/rubik/security/allowlist.rb +167 -0
- data/lib/rubik/security/audit_log.rb +72 -0
- data/lib/rubik/security/classifier/classifier.rb +8 -0
- data/lib/rubik/security/command_gate.rb +567 -0
- data/lib/rubik/security/guard.rb +88 -1075
- data/lib/rubik/security/path_policy.rb +117 -0
- data/lib/rubik/security/synthesis_gate.rb +300 -0
- data/lib/rubik/security.rb +5 -0
- data/lib/rubik/storage/ranking.rb +113 -0
- data/lib/rubik/storage/store.rb +2 -92
- data/lib/rubik/storage/transcript_indexer.rb +2 -3
- data/lib/rubik/tools/builtins/grep.rb +2 -3
- data/lib/rubik/tools/builtins/lifecycle.rb +90 -87
- data/lib/rubik/tools/builtins/synthesis.rb +3 -0
- data/lib/rubik/tools/lifecycle_rollbacks.rb +87 -0
- data/lib/rubik/tools/native_search.rb +2 -1
- data/lib/rubik/tools/truncator.rb +25 -0
- data/lib/rubik/version.rb +1 -1
- metadata +11 -1
|
@@ -16,12 +16,19 @@ module Rubik
|
|
|
16
16
|
# #stderr_tail for diagnostics.
|
|
17
17
|
STDERR_TAIL_LINES = 20
|
|
18
18
|
|
|
19
|
-
|
|
19
|
+
# Credential-shaped variable names stripped from the inherited host
|
|
20
|
+
# environment when a server opts out with `inherit_env: false`. Only
|
|
21
|
+
# the suffix shape is policy — the prefix is the provider's choice
|
|
22
|
+
# (GITHUB_TOKEN, ANTHROPIC_API_KEY, ...), so we match it broadly.
|
|
23
|
+
CREDENTIAL_ENV_PATTERN = /_(API_KEY|TOKEN|SECRET|PASSWORD)\z/i
|
|
20
24
|
|
|
21
|
-
|
|
25
|
+
attr_reader :command, :args, :env, :inherit_env, :root_dir, :running, :wait_thr
|
|
26
|
+
|
|
27
|
+
def initialize(command, args: [], env: {}, inherit_env: true, root_dir: Dir.pwd, guard: nil)
|
|
22
28
|
@command = command
|
|
23
29
|
@args = Array(args).map(&:to_s)
|
|
24
30
|
@env = env || {}
|
|
31
|
+
@inherit_env = self.class.coerce_inherit_env(inherit_env)
|
|
25
32
|
@root_dir = File.expand_path(root_dir)
|
|
26
33
|
@guard = guard || Rubik::Security::Guard.new
|
|
27
34
|
@running = false
|
|
@@ -82,14 +89,12 @@ module Rubik
|
|
|
82
89
|
resolved_bin = Rubik::Platform.which(bin)
|
|
83
90
|
cmd_parts[0] = resolved_bin if resolved_bin
|
|
84
91
|
|
|
85
|
-
|
|
86
|
-
|
|
92
|
+
# Match the LSP client's spawn hygiene: the host's bundler/Ruby
|
|
93
|
+
# runtime variables are unset for the child, so an MCP server never
|
|
94
|
+
# inherits a foreign BUNDLE_GEMFILE/RUBYOPT. Explicitly configured
|
|
95
|
+
# env: entries merge on top and win.
|
|
87
96
|
begin
|
|
88
|
-
@stdin, @stdout, @stderr, @wait_thr =
|
|
89
|
-
Open3.popen3(*cmd_parts, chdir: @root_dir)
|
|
90
|
-
else
|
|
91
|
-
Open3.popen3(string_env, *cmd_parts, chdir: @root_dir)
|
|
92
|
-
end
|
|
97
|
+
@stdin, @stdout, @stderr, @wait_thr = Open3.popen3(spawn_env, *cmd_parts, chdir: @root_dir)
|
|
93
98
|
rescue SystemCallError => e
|
|
94
99
|
raise ConnectionError, "Failed to spawn MCP process '#{bin}': #{e.message}"
|
|
95
100
|
end
|
|
@@ -251,8 +256,45 @@ module Rubik
|
|
|
251
256
|
@wait_thr&.pid
|
|
252
257
|
end
|
|
253
258
|
|
|
259
|
+
class << self
|
|
260
|
+
# Config coercion for `inherit_env:`: only an explicit false
|
|
261
|
+
# (boolean or the string/nil-safe "false") opts out; every other
|
|
262
|
+
# value — including nil and unknown types — keeps the inheriting
|
|
263
|
+
# default so hand-written config cannot accidentally widen the
|
|
264
|
+
# credential hole or break the spawn.
|
|
265
|
+
def coerce_inherit_env(value)
|
|
266
|
+
![false, "false"].include?(value)
|
|
267
|
+
end
|
|
268
|
+
end
|
|
269
|
+
|
|
254
270
|
private
|
|
255
271
|
|
|
272
|
+
# The environment the child runs in: the host's bundler/Ruby runtime
|
|
273
|
+
# variables are unset (Platform.sanitized_spawn_env — the same scrub
|
|
274
|
+
# list the LSP client applies), then explicitly configured env:
|
|
275
|
+
# entries merge on top and win.
|
|
276
|
+
#
|
|
277
|
+
# Credential policy: by default the child inherits the host env (minus
|
|
278
|
+
# the scrub list) because many MCP servers legitimately need operator
|
|
279
|
+
# credentials (GITHUB_TOKEN etc.). With `inherit_env: false` the child
|
|
280
|
+
# still inherits the host env, but credential-shaped variables
|
|
281
|
+
# (CREDENTIAL_ENV_PATTERN) are additionally unset — spawn override
|
|
282
|
+
# semantics need an explicit nil to remove an inherited variable —
|
|
283
|
+
# leaving the sanitized base plus ONLY the server's explicit env:
|
|
284
|
+
# entries for anything credential-shaped. Explicit env: entries always
|
|
285
|
+
# win in both modes.
|
|
286
|
+
def spawn_env
|
|
287
|
+
base = Rubik::Platform.sanitized_spawn_env
|
|
288
|
+
unless @inherit_env
|
|
289
|
+
ENV.each_key do |key|
|
|
290
|
+
base[key] = nil if key.match?(CREDENTIAL_ENV_PATTERN)
|
|
291
|
+
end
|
|
292
|
+
end
|
|
293
|
+
base.merge(
|
|
294
|
+
@env.transform_keys(&:to_s).transform_values(&:to_s)
|
|
295
|
+
)
|
|
296
|
+
end
|
|
297
|
+
|
|
256
298
|
def write_message(msg_hash)
|
|
257
299
|
json = JSON.dump(msg_hash)
|
|
258
300
|
@mutex.synchronize do
|
|
@@ -0,0 +1,505 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "securerandom"
|
|
4
|
+
require "time"
|
|
5
|
+
|
|
6
|
+
require_relative "../log"
|
|
7
|
+
require_relative "../platform"
|
|
8
|
+
require_relative "goal_state"
|
|
9
|
+
require_relative "goal_registry"
|
|
10
|
+
require_relative "goal_ledger"
|
|
11
|
+
|
|
12
|
+
module Rubik
|
|
13
|
+
module Orchestrator
|
|
14
|
+
# Goal-session domain (issue #404): the ONE home for the !goal run
|
|
15
|
+
# lifecycle — start (execute_goal), the shared turn driver
|
|
16
|
+
# (drive_goal_turn: budget extensions, the single error channel,
|
|
17
|
+
# terminal mapping), suspension plus both resume paths (in-process
|
|
18
|
+
# loop revival and cross-process Σ-window rehydration), the suspended
|
|
19
|
+
# -goal registry plumbing and the `!goal list` surface. Moved verbatim
|
|
20
|
+
# from REPL::Commands::AgentExecution; the command block keeps only
|
|
21
|
+
# argument parsing and delegates here.
|
|
22
|
+
#
|
|
23
|
+
# owns : goal start/suspend/resume/fail/complete choreography, the
|
|
24
|
+
# GoalState + Σ ledger + registry provide discipline, the
|
|
25
|
+
# honest-continuity output strings, the documented ordering
|
|
26
|
+
# contracts (ledger_id-before-suspend!, suspend_stamp_meta
|
|
27
|
+
# schema), and the single goal-shaped orchestrator-loop
|
|
28
|
+
# stanza (build_goal_orchestrator)
|
|
29
|
+
# leaves : command argument parsing and usage rendering
|
|
30
|
+
# (REPL::Commands::AgentExecution), the Loop machinery
|
|
31
|
+
# itself (Loop/GoalWait), and input_execution's streaming
|
|
32
|
+
# on_step stanza
|
|
33
|
+
module GoalSession
|
|
34
|
+
module_function
|
|
35
|
+
|
|
36
|
+
def initialize_goal_ledger(ctx, goal_text)
|
|
37
|
+
return nil unless Rubik::Orchestrator::GoalLedger::Ledger.enabled?(ctx.config)
|
|
38
|
+
|
|
39
|
+
store = Rubik::Coeffects.get(ctx.runtime_manager&.context, Rubik::Coeffects::STORAGE_STORE)
|
|
40
|
+
dmesg = Rubik::Coeffects.get(ctx.runtime_manager&.context, Rubik::Coeffects::DMESG)
|
|
41
|
+
goal_ledger = Rubik::Orchestrator::GoalLedger::Ledger.create!(
|
|
42
|
+
goal_text: goal_text, config: ctx.config, store: store, dmesg: dmesg,
|
|
43
|
+
event_bus: ctx.event_bus
|
|
44
|
+
)
|
|
45
|
+
ctx.runtime_manager.provide(Rubik::Coeffects::GOAL_LEDGER, goal_ledger)
|
|
46
|
+
goal_ledger
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
def execute_goal(ctx, goal_text, custom_steps)
|
|
50
|
+
ctx.recorder&.record_user_turn("!goal #{goal_text}")
|
|
51
|
+
goal_steps = custom_steps || ctx.config.fetch("agent.goal_max_steps", 100).to_i
|
|
52
|
+
routed = ctx.router.route(task_type: :goal, prompt: goal_text)
|
|
53
|
+
ctx.runtime_manager.provide(:llm_client, routed[:provider]) if routed[:provider]
|
|
54
|
+
|
|
55
|
+
# Canlı hedef durumu: maestro ve alt ajanlar read_file
|
|
56
|
+
# rubik://goal/state ile aynı anlık görüntüyü okur. Provide swap
|
|
57
|
+
# semantiğine sahiptir — tekrarlanan !goal koşuları Ω'ya inverse
|
|
58
|
+
# yığmaz; session dispose'u tek delete-inverse ile temizler.
|
|
59
|
+
# event_bus: bitiş olayı (GoalState::FINISH_EVENT) Vakanüvis
|
|
60
|
+
# kronikçisinin goal kancasına akar (K3) — notice/wake yok.
|
|
61
|
+
goal_state = Rubik::Orchestrator::GoalState.new(event_bus: ctx.event_bus)
|
|
62
|
+
goal_state.start!(goal_text, goal_steps)
|
|
63
|
+
ctx.runtime_manager.provide(Rubik::Coeffects::GOAL_STATE, goal_state)
|
|
64
|
+
|
|
65
|
+
# Yapılandırılmış Σ defteri (goal-ledger planı A): knob ON iken
|
|
66
|
+
# koşuyla doğar, terminal dallarda finalize olur, provide swap
|
|
67
|
+
# semantiğiyle tekrarlanan !goal koşuları Ω'ya inverse yığmaz.
|
|
68
|
+
# OFF iken hiçbir yüz kurulmaz (araç/URI/prompt bayt-özdeş).
|
|
69
|
+
goal_ledger = initialize_goal_ledger(ctx, goal_text)
|
|
70
|
+
|
|
71
|
+
# Askı kimliği (issue #106): koşu boyunca SABİT — registry
|
|
72
|
+
# girdisinin anahtarı ve Σ damgası meta'sının goal_id'si.
|
|
73
|
+
# (Σ satır id'si her kabulde değişir; kimlik olarak kullanılamaz.)
|
|
74
|
+
goal_id = "goal-#{Process.pid}-#{SecureRandom.hex(4)}"
|
|
75
|
+
|
|
76
|
+
ctx.out.puts "[Rubik::Goal] Starting autonomous goal loop (Budget: #{goal_steps} steps) with #{routed[:role]} model (#{routed[:model]})..."
|
|
77
|
+
ctx.out.puts "[Rubik::Goal] Target: #{goal_text}\n"
|
|
78
|
+
|
|
79
|
+
orchestrator = build_goal_orchestrator(ctx, goal_state: goal_state, routed: routed, steps: goal_steps)
|
|
80
|
+
|
|
81
|
+
# Plan 53 D-8 yardımcısı: nötr çift + kayıtçı eşlemesi tek yerde.
|
|
82
|
+
# Session restore kayıtçı OLAYLARINDAN hidrate eder — eşlenmiş
|
|
83
|
+
# restore için conversation_history VE record_assistant_response
|
|
84
|
+
# birlikte yazılmalı (başarısızlıkta da).
|
|
85
|
+
record_goal_pair = build_goal_record_pair(ctx, goal_text)
|
|
86
|
+
|
|
87
|
+
# Pruner apply seam: hedef döngüsü de aynı sınırda tohumlanır —
|
|
88
|
+
# aşamalı budama planı varsa goal promptundan ÖNCE uygulanır.
|
|
89
|
+
ctx.apply_staged_prune_plan!
|
|
90
|
+
|
|
91
|
+
drive_goal_turn(ctx, orchestrator: orchestrator, goal_state: goal_state,
|
|
92
|
+
goal_ledger: goal_ledger, goal_text: goal_text, goal_id: goal_id,
|
|
93
|
+
record_pair: record_goal_pair,
|
|
94
|
+
start: ->(loop_inst) { loop_inst.run(goal_text, goal_mode: true, conversation_history: ctx.conversation_history) })
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
# ------------------------------------------------------------------
|
|
98
|
+
# !goal sürücüsü (issue #106): koşu girişi + bütçe-soru döngüsü +
|
|
99
|
+
# tek hata kanalı + terminal eşlemesi — start ve resume yollarının
|
|
100
|
+
# ORTAK gövdesi. start callable'ı yolu seçer:
|
|
101
|
+
# başlangıç → loop.run (taze koşu)
|
|
102
|
+
# süreç-içi resume → loop.resume! (history prefix nesne-özdeş)
|
|
103
|
+
# çapraz-süreç resume → loop.resume_from (Σ penceresi)
|
|
104
|
+
# Askı dalı (#106): SADECE transient ClientError SUSPENDED'a gider;
|
|
105
|
+
# kalıcı hatalar (moderasyon/401/read-timeout) bugünkü fail_goal
|
|
106
|
+
# çıktısını bayt-baytına korur.
|
|
107
|
+
def drive_goal_turn(ctx, orchestrator:, goal_state:, goal_ledger:,
|
|
108
|
+
goal_text:, goal_id:, record_pair:, start:)
|
|
109
|
+
ctx.active_loop = orchestrator
|
|
110
|
+
begin
|
|
111
|
+
res = start.call(orchestrator)
|
|
112
|
+
res = handle_goal_budget_extensions(ctx, orchestrator: orchestrator, goal_state: goal_state, res: res)
|
|
113
|
+
rescue Interrupt
|
|
114
|
+
# ^C hedefi 'running' bırakmasın; eşlenmiş kayıt otursun. Interrupt
|
|
115
|
+
# yeniden yükselir — kullanıcı mesajını execute_command basar.
|
|
116
|
+
# Resume üstüne ^C = askıyı terk (terminal :stopped damgası).
|
|
117
|
+
goal_state.stop!("Interrupted by user (^C)")
|
|
118
|
+
finalize_goal_ledger(goal_ledger, goal_state, :stopped)
|
|
119
|
+
forget_suspended_goal(ctx, goal_id)
|
|
120
|
+
record_pair.call("[Goal attempt interrupted after #{goal_state.step_count} steps]")
|
|
121
|
+
raise
|
|
122
|
+
rescue Rubik::LLM::ClientError => e
|
|
123
|
+
# Tek hata kanalı (#106 uzantısı): transient transport hatası
|
|
124
|
+
# (RETRYABLE tükenmesi, tükenmiş 5xx, 429) goal'u SUSPENDED'a
|
|
125
|
+
# götürür — loop/counters/Σ korunur, REPL yaşar. Kalıcı hata
|
|
126
|
+
# (#105 çıktısı değişmeden) terminal fail. Yeniden yükseltmez —
|
|
127
|
+
# spinner temizliği dispatch katmanına (execute_command) aittir.
|
|
128
|
+
# next yerine return: rescue sonrası res'siz terminal
|
|
129
|
+
# eşlemesine düşülmesin.
|
|
130
|
+
if e.respond_to?(:transient?) && e.transient?
|
|
131
|
+
suspend_goal_turn(ctx, orchestrator: orchestrator, goal_state: goal_state, goal_ledger: goal_ledger,
|
|
132
|
+
goal_text: goal_text, goal_id: goal_id, record_pair: record_pair, reason: e.message,
|
|
133
|
+
tokens: orchestrator.total_tokens)
|
|
134
|
+
else
|
|
135
|
+
fail_goal_turn(ctx, goal_state: goal_state, goal_ledger: goal_ledger, goal_id: goal_id,
|
|
136
|
+
record_pair: record_pair, reason: e.message)
|
|
137
|
+
end
|
|
138
|
+
return
|
|
139
|
+
rescue StandardError => e
|
|
140
|
+
fail_goal_turn(ctx, goal_state: goal_state, goal_ledger: goal_ledger, goal_id: goal_id,
|
|
141
|
+
record_pair: record_pair, reason: "#{e.class}: #{e.message}")
|
|
142
|
+
return
|
|
143
|
+
ensure
|
|
144
|
+
ctx.active_loop = nil
|
|
145
|
+
end
|
|
146
|
+
|
|
147
|
+
handle_goal_completion(ctx, res: res, goal_state: goal_state, goal_ledger: goal_ledger,
|
|
148
|
+
goal_id: goal_id, record_pair: record_pair)
|
|
149
|
+
end
|
|
150
|
+
|
|
151
|
+
def finalize_goal_ledger(goal_ledger, goal_state, status)
|
|
152
|
+
return unless goal_ledger
|
|
153
|
+
|
|
154
|
+
goal_ledger.finalize!(status)
|
|
155
|
+
goal_state.ledger_id = goal_ledger.snapshot[:storage_id]
|
|
156
|
+
end
|
|
157
|
+
|
|
158
|
+
def fail_goal_turn(ctx, goal_state:, goal_ledger:, goal_id:, record_pair:,
|
|
159
|
+
reason:, tokens: nil, steps: nil)
|
|
160
|
+
sanitized = Rubik::Platform.safe_utf8(reason.to_s)
|
|
161
|
+
steps_used = steps || goal_state.step_count
|
|
162
|
+
goal_state.fail!(sanitized, tokens: tokens)
|
|
163
|
+
finalize_goal_ledger(goal_ledger, goal_state, :failed)
|
|
164
|
+
forget_suspended_goal(ctx, goal_id)
|
|
165
|
+
ctx.out.puts "\n❌ Goal could not be completed: #{sanitized}"
|
|
166
|
+
record_pair.call("[Goal attempt ended after #{steps_used} steps: #{sanitized}]", tokens: tokens)
|
|
167
|
+
end
|
|
168
|
+
|
|
169
|
+
def suspend_goal_turn(ctx, orchestrator:, goal_state:, goal_ledger:,
|
|
170
|
+
goal_text:, goal_id:, record_pair:, reason:, tokens: nil)
|
|
171
|
+
attempt = suspended_attempt(ctx, goal_id) + 1
|
|
172
|
+
# Ledger kimliği askıdan ÖNCE okunur: suspend! → ledger.suspend!
|
|
173
|
+
# sırası metanın bu turun token'larını içermesi için zorunlu,
|
|
174
|
+
# ama o damga storage_id'yi değiştirdiği için sonradan atanan id
|
|
175
|
+
# SUSPEND_EVENT'e geç kalırdı — ilk askıda kronik satırı slug
|
|
176
|
+
# kimliğine düşer, ledger= bağlantısı kaybolurdu.
|
|
177
|
+
# resume_cross_process ile aynı uçuş-içi atama önceliği.
|
|
178
|
+
goal_state.ledger_id = goal_ledger.snapshot[:storage_id] if goal_ledger
|
|
179
|
+
goal_state.suspend!(reason, tokens: tokens)
|
|
180
|
+
goal_ledger&.suspend!(suspend_stamp_meta(goal_state, goal_id, reason, attempt))
|
|
181
|
+
registry = goal_registry_for(ctx)
|
|
182
|
+
registry.register(Rubik::Orchestrator::GoalRegistry::Entry.new(
|
|
183
|
+
goal_id: goal_id, goal_text: goal_text, loop: orchestrator,
|
|
184
|
+
goal_state: goal_state, ledger: goal_ledger, reason: reason.to_s,
|
|
185
|
+
suspended_at: Time.now, attempt: attempt
|
|
186
|
+
))
|
|
187
|
+
ctx.out.puts "\n⏸️ [Rubik::Goal] Suspended after #{goal_state.step_count} steps (transient provider error): #{reason}"
|
|
188
|
+
ctx.out.puts " Loop, counters and Σ ledger are preserved — resume with `!goal resume`."
|
|
189
|
+
record_pair.call("[Goal suspended after #{goal_state.step_count} steps: #{reason}]", tokens: tokens)
|
|
190
|
+
end
|
|
191
|
+
|
|
192
|
+
def handle_goal_budget_extensions(ctx, orchestrator:, goal_state:, res:)
|
|
193
|
+
# Bütçe tükenince sor (execute_free_text simetrisi; aynı knob,
|
|
194
|
+
# aynı +20). continue_loop boyunca active_loop DOLU kalmalı:
|
|
195
|
+
# notice yönlendirmesi aktif döngüye bakar (lifecycle.rb
|
|
196
|
+
# route_subagent_notice) — soruya beklerken gelen subagent
|
|
197
|
+
# olayları loop inbox'a girer ve devam adımında boşaltılır.
|
|
198
|
+
auto_extensions = 0
|
|
199
|
+
max_auto = ctx.config.fetch("agent.goal_auto_continue_limit", 0).to_i
|
|
200
|
+
# Yapılandırılmış neden (loop.rb terminali): insan-okur string
|
|
201
|
+
# yalnız gösterim içindir — otomasyon prozu parse etmesin.
|
|
202
|
+
while !res[:ok] && res[:reason] == :budget_exhausted
|
|
203
|
+
if auto_extensions < max_auto
|
|
204
|
+
auto_extensions += 1
|
|
205
|
+
ctx.out.puts "\n🤖 [Rubik::Goal] Adım bütçesi doldu (#{res[:error]}). " \
|
|
206
|
+
"Otonom devam hakkı (#{auto_extensions}/#{max_auto}) kullanılarak +20 adım ekleniyor..."
|
|
207
|
+
goal_state.extend!(goal_state.max_steps + 20)
|
|
208
|
+
res = orchestrator.continue_loop(20, auto: true)
|
|
209
|
+
next
|
|
210
|
+
end
|
|
211
|
+
|
|
212
|
+
break unless ctx.config.fetch("agent.ask_continue_on_limit", true)
|
|
213
|
+
|
|
214
|
+
ctx.out.puts "\n⚠️ [Rubik::Goal] #{res[:error]}"
|
|
215
|
+
ans = ctx.ask_yes_no(" [Rubik::Goal] +20 adım ile devam edilsin mi?", default: "n")
|
|
216
|
+
break unless ["y", "yes", "evet"].include?(ans)
|
|
217
|
+
|
|
218
|
+
ctx.out.puts " [Rubik::Goal] Adım bütçesi +20 artırılıyor ve hedef sürdürülüyor..."
|
|
219
|
+
goal_state.extend!(goal_state.max_steps + 20)
|
|
220
|
+
res = orchestrator.continue_loop(20)
|
|
221
|
+
end
|
|
222
|
+
res
|
|
223
|
+
end
|
|
224
|
+
|
|
225
|
+
def handle_goal_completion(ctx, res:, goal_state:, goal_ledger:,
|
|
226
|
+
goal_id:, record_pair:)
|
|
227
|
+
if res[:ok]
|
|
228
|
+
active = goal_active_subagent_count(ctx)
|
|
229
|
+
if active.positive?
|
|
230
|
+
# Defense behind the loop-level goal guard (GoalWait): a
|
|
231
|
+
# success terminal escaping with live subagents means the
|
|
232
|
+
# pipeline is mid-flight — an honest stop beats a false
|
|
233
|
+
# "Goal Achieved" (field incident 2026-10-05).
|
|
234
|
+
reason = "Goal loop concluded with #{active} active subagent(s) still running — not marked complete"
|
|
235
|
+
goal_state.stop!(reason)
|
|
236
|
+
finalize_goal_ledger(goal_ledger, goal_state, :stopped)
|
|
237
|
+
ctx.out.puts "\n⚠️ [Rubik::Goal] #{reason}."
|
|
238
|
+
record_pair.call("[Goal attempt ended after #{goal_state.step_count} steps: #{reason}]", tokens: res[:tokens])
|
|
239
|
+
else
|
|
240
|
+
goal_state.complete!(res[:output].to_s, tokens: res[:tokens])
|
|
241
|
+
finalize_goal_ledger(goal_ledger, goal_state, :completed)
|
|
242
|
+
forget_suspended_goal(ctx, goal_id)
|
|
243
|
+
ctx.out.puts "\n🎉 Goal Achieved in #{res[:steps]} steps!"
|
|
244
|
+
ctx.out.puts res[:output]
|
|
245
|
+
# Keep the bang syntax out of the LLM context (Plan 53 D-8): the
|
|
246
|
+
# session recorder already stores the literal "!goal ..." for replay.
|
|
247
|
+
record_pair.call(res[:output].to_s, streamed: res[:streamed] == true, tokens: res[:tokens])
|
|
248
|
+
|
|
249
|
+
ctx.out.puts "\nTip: Use `!diff` to review changes and `!apply` to commit to disk." if ctx.buffer_manager.dirty?
|
|
250
|
+
end
|
|
251
|
+
else
|
|
252
|
+
# Başarısızlık eşlemesi yukarıdaki tek hata kanalından akar:
|
|
253
|
+
# GoalState → ledger finalize → kayıtçı çifti, istisna yoluyla
|
|
254
|
+
# aynı sırayla.
|
|
255
|
+
fail_goal_turn(ctx, goal_state: goal_state, goal_ledger: goal_ledger, goal_id: goal_id,
|
|
256
|
+
record_pair: record_pair, reason: res[:error], tokens: res[:tokens], steps: res[:steps])
|
|
257
|
+
end
|
|
258
|
+
end
|
|
259
|
+
|
|
260
|
+
# ------------------------------------------------------------------
|
|
261
|
+
# !goal resume (issue #106). İki yol, dönüşüm sırasına göre:
|
|
262
|
+
# 1) Oturum kaydında canlı girdi varsa süreç-içi resume — hayatta
|
|
263
|
+
# kalan Loop örneği canlandırılır (subagent konuşmaları gerçekten
|
|
264
|
+
# süreklidir; süpervizör sürecin yaşıyor).
|
|
265
|
+
# 2) Yoksa çapraz-süreç Σ-only resume — storage'daki "suspended"
|
|
266
|
+
# satırından rehidrasyon. Alt ajan konuşmaları süreçle ölür;
|
|
267
|
+
# çıktı bunu tek cümleyle dürüstçe söyler.
|
|
268
|
+
def resume_suspended_goal(ctx)
|
|
269
|
+
registry = Rubik::Coeffects.get(ctx.runtime_manager&.context, Rubik::Coeffects::GOAL_REGISTRY)
|
|
270
|
+
entry = registry.latest if registry.is_a?(Rubik::Orchestrator::GoalRegistry)
|
|
271
|
+
entry ? resume_in_process(ctx, entry) : resume_cross_process(ctx)
|
|
272
|
+
end
|
|
273
|
+
|
|
274
|
+
def resume_in_process(ctx, entry)
|
|
275
|
+
ctx.recorder&.record_user_turn("!goal resume")
|
|
276
|
+
goal_state = entry.goal_state
|
|
277
|
+
goal_ledger = entry.ledger
|
|
278
|
+
ctx.runtime_manager.provide(Rubik::Coeffects::GOAL_STATE, goal_state)
|
|
279
|
+
ctx.runtime_manager.provide(Rubik::Coeffects::GOAL_LEDGER, goal_ledger) if goal_ledger
|
|
280
|
+
goal_ledger&.unsuspend!
|
|
281
|
+
goal_state.resume!
|
|
282
|
+
ctx.out.puts "[Rubik::Goal] Resuming '#{entry.goal_text}' (attempt #{entry.attempt + 1}, " \
|
|
283
|
+
"suspended: #{entry.reason})"
|
|
284
|
+
# Dürüst süreklilik cümlesi: alt ajan konuşmaları süreç-içi
|
|
285
|
+
# resume'da yaşar — çapraz-süreç yoldaki tek cümlelik uyarı burada
|
|
286
|
+
# YOKTUR (gerçek süreklilik).
|
|
287
|
+
record_pair = build_goal_record_pair(ctx, entry.goal_text)
|
|
288
|
+
ctx.apply_staged_prune_plan!
|
|
289
|
+
drive_goal_turn(ctx, orchestrator: entry.loop, goal_state: goal_state,
|
|
290
|
+
goal_ledger: goal_ledger, goal_text: entry.goal_text,
|
|
291
|
+
goal_id: entry.goal_id, record_pair: record_pair,
|
|
292
|
+
start: lambda { |loop_inst|
|
|
293
|
+
loop_inst.resume!(reason: entry.reason,
|
|
294
|
+
suspended_at: entry.suspended_at,
|
|
295
|
+
attempt: entry.attempt)
|
|
296
|
+
})
|
|
297
|
+
end
|
|
298
|
+
|
|
299
|
+
def resume_cross_process(ctx)
|
|
300
|
+
ctx.recorder&.record_user_turn("!goal resume")
|
|
301
|
+
store = Rubik::Coeffects.get(ctx.runtime_manager&.context, Rubik::Coeffects::STORAGE_STORE)
|
|
302
|
+
unless store
|
|
303
|
+
ctx.out.puts "ℹ️ [Rubik::Goal] No suspended goal in this session; storage unavailable — " \
|
|
304
|
+
"cross-process resume honestly refused."
|
|
305
|
+
return
|
|
306
|
+
end
|
|
307
|
+
|
|
308
|
+
row = suspended_rows(store).last
|
|
309
|
+
unless row
|
|
310
|
+
ctx.out.puts "ℹ️ [Rubik::Goal] No suspended goal found (session registry empty, no 'suspended' Σ rows)."
|
|
311
|
+
return
|
|
312
|
+
end
|
|
313
|
+
|
|
314
|
+
dmesg = Rubik::Coeffects.get(ctx.runtime_manager&.context, Rubik::Coeffects::DMESG)
|
|
315
|
+
ledger = Rubik::Orchestrator::GoalLedger::Ledger.load(store: store, storage_id: row.id,
|
|
316
|
+
config: ctx.config, dmesg: dmesg,
|
|
317
|
+
event_bus: ctx.event_bus)
|
|
318
|
+
unless ledger
|
|
319
|
+
ctx.out.puts "⚠️ [Rubik::Goal] Suspended goal row #{row.id} could not be rehydrated — " \
|
|
320
|
+
"cross-process resume refused (corrupt or non-suspended stamp)."
|
|
321
|
+
return
|
|
322
|
+
end
|
|
323
|
+
|
|
324
|
+
meta = ledger.suspend_meta || {}
|
|
325
|
+
goal_text = ledger.snapshot[:objective].to_s
|
|
326
|
+
goal_steps = meta["max_steps"].to_i.positive? ? meta["max_steps"].to_i : ctx.config.fetch("agent.goal_max_steps", 100).to_i
|
|
327
|
+
goal_state = Rubik::Orchestrator::GoalState.new(event_bus: ctx.event_bus)
|
|
328
|
+
goal_state.start!(goal_text, goal_steps)
|
|
329
|
+
goal_state.restore_counters!(steps: meta["steps"], max_steps: goal_steps,
|
|
330
|
+
extensions: meta["extensions"], tokens: meta["tokens"])
|
|
331
|
+
goal_state.ledger_id = ledger.snapshot[:storage_id]
|
|
332
|
+
ctx.runtime_manager.provide(Rubik::Coeffects::GOAL_STATE, goal_state)
|
|
333
|
+
ctx.runtime_manager.provide(Rubik::Coeffects::GOAL_LEDGER, ledger)
|
|
334
|
+
|
|
335
|
+
routed = ctx.router.route(task_type: :goal, prompt: goal_text)
|
|
336
|
+
ctx.runtime_manager.provide(:llm_client, routed[:provider]) if routed[:provider]
|
|
337
|
+
orchestrator = build_goal_orchestrator(ctx, goal_state: goal_state, routed: routed, steps: goal_steps)
|
|
338
|
+
|
|
339
|
+
ctx.out.puts "[Rubik::Goal] Cross-process resume of '#{goal_text}' (attempt #{meta['attempt'].to_i})..."
|
|
340
|
+
# Dürüst süreklilik cümlesi (tasarım sözleşmesi): alt ajan
|
|
341
|
+
# konuşmaları süreçle öldü; disk etkileri ve session kaydı yaşar.
|
|
342
|
+
ctx.out.puts " Subagent conversations did not survive the process restart — their disk " \
|
|
343
|
+
"effects and the session record have."
|
|
344
|
+
ledger.unsuspend!
|
|
345
|
+
record_pair = build_goal_record_pair(ctx, goal_text)
|
|
346
|
+
ctx.apply_staged_prune_plan!
|
|
347
|
+
drive_goal_turn(ctx, orchestrator: orchestrator, goal_state: goal_state,
|
|
348
|
+
goal_ledger: ledger, goal_text: goal_text,
|
|
349
|
+
goal_id: meta["goal_id"].to_s.empty? ? row.id : meta["goal_id"],
|
|
350
|
+
record_pair: record_pair,
|
|
351
|
+
start: lambda { |loop_inst|
|
|
352
|
+
loop_inst.resume_from(goal_text: goal_text, ledger: ledger,
|
|
353
|
+
reason: meta["reason"].to_s,
|
|
354
|
+
suspended_at: parse_suspended_at(meta["suspended_at"]),
|
|
355
|
+
attempt: meta["attempt"].to_i,
|
|
356
|
+
counters: { steps: meta["steps"], max_steps: goal_steps,
|
|
357
|
+
tokens: meta["tokens"] })
|
|
358
|
+
})
|
|
359
|
+
end
|
|
360
|
+
|
|
361
|
+
# !goal list (issue #106 Faz 2a): store'daki status == "suspended"
|
|
362
|
+
# Σ satırları — özetler zaten status taşıyor (Store::Summary).
|
|
363
|
+
def list_suspended_goals(ctx)
|
|
364
|
+
ctx.recorder&.record_user_turn("!goal list")
|
|
365
|
+
store = Rubik::Coeffects.get(ctx.runtime_manager&.context, Rubik::Coeffects::STORAGE_STORE)
|
|
366
|
+
unless store
|
|
367
|
+
ctx.out.puts "ℹ️ [Rubik::Goal] Storage unavailable — the suspended-goal list needs goal.ledger storage."
|
|
368
|
+
return
|
|
369
|
+
end
|
|
370
|
+
|
|
371
|
+
rows = suspended_rows(store)
|
|
372
|
+
if rows.empty?
|
|
373
|
+
ctx.out.puts "ℹ️ [Rubik::Goal] No suspended goals."
|
|
374
|
+
return
|
|
375
|
+
end
|
|
376
|
+
|
|
377
|
+
ctx.out.puts "=== Suspended goals ==="
|
|
378
|
+
rows.each do |s|
|
|
379
|
+
ctx.out.puts " #{s.id} #{s.updated_at} #{s.title}"
|
|
380
|
+
end
|
|
381
|
+
ctx.out.puts "Resume the latest with: !goal resume"
|
|
382
|
+
end
|
|
383
|
+
|
|
384
|
+
# Askı satırları: en eski → en yeni sıralı (updated_at; kuiratör
|
|
385
|
+
# list yüzeyiyle aynı alan). Sort anahtarı eşitse row sırası.
|
|
386
|
+
def suspended_rows(store)
|
|
387
|
+
store.list(type: "goal").select { |s| s.status == "suspended" }.sort_by(&:updated_at)
|
|
388
|
+
end
|
|
389
|
+
|
|
390
|
+
# Σ damgası meta'sı (issue #106): {goal_id, steps, max_steps,
|
|
391
|
+
# extensions, tokens, reason, suspended_at, attempt}. Sembol
|
|
392
|
+
# anahtarlar Ledger#suspend! içinde dizgeleştirilir.
|
|
393
|
+
def suspend_stamp_meta(goal_state, goal_id, reason, attempt)
|
|
394
|
+
{ goal_id: goal_id, steps: goal_state.step_count, max_steps: goal_state.max_steps,
|
|
395
|
+
extensions: goal_state.extensions, tokens: goal_state.tokens.dup,
|
|
396
|
+
reason: reason.to_s.slice(0, 300), suspended_at: Time.now.utc.iso8601, attempt: attempt }
|
|
397
|
+
end
|
|
398
|
+
|
|
399
|
+
def suspended_attempt(ctx, goal_id)
|
|
400
|
+
registry = Rubik::Coeffects.get(ctx.runtime_manager&.context, Rubik::Coeffects::GOAL_REGISTRY)
|
|
401
|
+
registry&.fetch(goal_id)&.attempt.to_i
|
|
402
|
+
end
|
|
403
|
+
|
|
404
|
+
# Oturum kaydı coeffect'i: ilk askıda provide edilir (provide-swap
|
|
405
|
+
# semantiği — Context#provide anahtar başına TEK delete-inverse
|
|
406
|
+
# tutar; tekrarlanan suspend/resume Ω'yı büyütmez).
|
|
407
|
+
def goal_registry_for(ctx)
|
|
408
|
+
registry = Rubik::Coeffects.get(ctx.runtime_manager&.context, Rubik::Coeffects::GOAL_REGISTRY)
|
|
409
|
+
return registry if registry.is_a?(Rubik::Orchestrator::GoalRegistry)
|
|
410
|
+
|
|
411
|
+
registry = Rubik::Orchestrator::GoalRegistry.new
|
|
412
|
+
ctx.runtime_manager&.provide(Rubik::Coeffects::GOAL_REGISTRY, registry)
|
|
413
|
+
registry
|
|
414
|
+
end
|
|
415
|
+
|
|
416
|
+
# Terminal yollarda girdi temizliği: kayıt SADECE sağlanmışsa —
|
|
417
|
+
# askı hiç yaşanmamış bir koşunun terminali boş registry provide
|
|
418
|
+
# ETMEMELİ (Ω disiplini).
|
|
419
|
+
def forget_suspended_goal(ctx, goal_id)
|
|
420
|
+
registry = Rubik::Coeffects.get(ctx.runtime_manager&.context, Rubik::Coeffects::GOAL_REGISTRY)
|
|
421
|
+
registry.delete(goal_id) if registry.is_a?(Rubik::Orchestrator::GoalRegistry)
|
|
422
|
+
end
|
|
423
|
+
|
|
424
|
+
# Adım olayı lambda'sı (start + cross-process resume ortak): sayaç
|
|
425
|
+
# akışı, kayıtçı tool çiftleri, render — start yolundaki satır içi
|
|
426
|
+
# gövdenin birebir taşınması.
|
|
427
|
+
def build_goal_on_step(ctx, goal_state)
|
|
428
|
+
lambda { |step_info|
|
|
429
|
+
# Adım sayacı rubik://goal/state'e aksın: olaylar bir adım
|
|
430
|
+
# içinde tekrarlanabilir, GoalState monotoniktir (zararsız).
|
|
431
|
+
goal_state.update_steps(step_info[:step], step_info[:max_steps]) if step_info[:step].is_a?(Integer)
|
|
432
|
+
# Session teşhis edilebilirliği (field incident 2026-10-12):
|
|
433
|
+
# saatler süren !goal koşuları session dosyasına tek satır
|
|
434
|
+
# düşürüyordu — free-text turn simetrisinde tool adımları
|
|
435
|
+
# kayıtçıya akar; render ve LLM geçmişi değişmez.
|
|
436
|
+
case step_info[:type]&.to_sym
|
|
437
|
+
when :tool_call
|
|
438
|
+
ctx.recorder&.record_tool_call(step_info[:tool], step_info[:args], call_id: step_info[:call_id])
|
|
439
|
+
when :tool_result
|
|
440
|
+
ctx.recorder&.record_tool_result(step_info[:tool], step_info[:output], status: step_info[:status] || :ok, call_id: step_info[:call_id])
|
|
441
|
+
end
|
|
442
|
+
ctx.render_step_event(step_info)
|
|
443
|
+
}
|
|
444
|
+
end
|
|
445
|
+
|
|
446
|
+
# Plan 53 D-8 yardımcısı: nötr çift + kayıtçı eşlemesi tek yerde.
|
|
447
|
+
# Session restore kayıtçı OLAYLARINDAN hidrate eder — eşlenmiş
|
|
448
|
+
# restore için conversation_history VE record_assistant_response
|
|
449
|
+
# birlikte yazılmalı (başarısızlıkta da).
|
|
450
|
+
def build_goal_record_pair(ctx, goal_text)
|
|
451
|
+
lambda do |assistant_content, streamed: nil, tokens: nil|
|
|
452
|
+
ctx.conversation_history << { role: "user", content: "Goal: #{goal_text}" }
|
|
453
|
+
ctx.conversation_history << { role: "assistant", content: assistant_content }
|
|
454
|
+
ctx.recorder&.record_assistant_response(assistant_content, tokens: tokens, streamed: streamed)
|
|
455
|
+
ctx.trim_conversation_window!
|
|
456
|
+
end
|
|
457
|
+
end
|
|
458
|
+
|
|
459
|
+
# The goal-shaped orchestrator-loop stanza's single home (issue #404).
|
|
460
|
+
# execute_goal (fresh run) and resume_cross_process (Σ-window
|
|
461
|
+
# rehydration) build the SAME shape — orchestrator_loop +
|
|
462
|
+
# warn_at_ratio + the goal on_step lambda — so the construction is
|
|
463
|
+
# folded here once. The plan command (render-only on_step, no
|
|
464
|
+
# warn_at_ratio) and input_execution (streaming on_step) keep their
|
|
465
|
+
# materially different stanzas inline at their own sites.
|
|
466
|
+
def build_goal_orchestrator(ctx, goal_state:, routed:, steps:)
|
|
467
|
+
warn_ratio = ctx.config.fetch("agent.warn_at_ratio", 0.75).to_f
|
|
468
|
+
ctx.orchestrator_loop(
|
|
469
|
+
provider: routed[:provider],
|
|
470
|
+
model: routed[:model],
|
|
471
|
+
max_steps: steps,
|
|
472
|
+
warn_at_ratio: warn_ratio,
|
|
473
|
+
context_limit: routed[:context_limit],
|
|
474
|
+
max_output_tokens: routed[:max_output_tokens],
|
|
475
|
+
on_step: build_goal_on_step(ctx, goal_state)
|
|
476
|
+
)
|
|
477
|
+
end
|
|
478
|
+
private_class_method :build_goal_orchestrator
|
|
479
|
+
|
|
480
|
+
# Damga meta'sındaki suspended_at (iso8601) → Time; bozuk değer
|
|
481
|
+
# nil — Loop#append_resume_marker! "unknown" downtime basar.
|
|
482
|
+
def parse_suspended_at(value)
|
|
483
|
+
Time.iso8601(value.to_s)
|
|
484
|
+
rescue ArgumentError, TypeError
|
|
485
|
+
nil
|
|
486
|
+
end
|
|
487
|
+
|
|
488
|
+
# Defense-in-depth behind the loop-level goal guard: if a success
|
|
489
|
+
# terminal escapes GoalWait with live subagent units, the goal must
|
|
490
|
+
# stop honestly instead of celebrating a false completion. Fails
|
|
491
|
+
# CONSERVATIVE: coeffect absence is nil-safe (Coeffects.get never
|
|
492
|
+
# raises for a missing subsystem), so a raise here is real breakage
|
|
493
|
+
# — reporting zero would launder it into exactly the false
|
|
494
|
+
# "Goal Achieved" this backstop exists to refuse.
|
|
495
|
+
def goal_active_subagent_count(ctx)
|
|
496
|
+
supervisor = Rubik::Coeffects.get(ctx.runtime_manager&.context, Rubik::Coeffects::SUBAGENT_SUPERVISOR)
|
|
497
|
+
supervisor&.active_count.to_i
|
|
498
|
+
rescue StandardError => e
|
|
499
|
+
Rubik::Log.warn(:orchestrator, "goal completion defense could not inspect subagents " \
|
|
500
|
+
"(#{e.class}: #{e.message}); refusing completion")
|
|
501
|
+
1
|
|
502
|
+
end
|
|
503
|
+
end
|
|
504
|
+
end
|
|
505
|
+
end
|
|
@@ -165,6 +165,10 @@ module Rubik
|
|
|
165
165
|
grant_budget!(additional_steps, note: ->(extra, total) { Budget.message_grant_note(extra, total) })
|
|
166
166
|
end
|
|
167
167
|
end
|
|
168
|
+
# Broadcast OUTSIDE the critical section (budget-pause discipline):
|
|
169
|
+
# wakes a questioner waiting on the answer. Spurious wakeups are
|
|
170
|
+
# harmless — the waiter rechecks @inbox and its state guards.
|
|
171
|
+
notify_answer!
|
|
168
172
|
end
|
|
169
173
|
|
|
170
174
|
def resume!(additional_steps: nil)
|
|
@@ -7,6 +7,7 @@ require "fileutils"
|
|
|
7
7
|
require_relative "../../platform"
|
|
8
8
|
require_relative "../../security/redactor"
|
|
9
9
|
require_relative "../../storage/layout"
|
|
10
|
+
require_relative "../../tools/truncator"
|
|
10
11
|
|
|
11
12
|
module Rubik
|
|
12
13
|
module Orchestrator
|
|
@@ -304,7 +305,7 @@ module Rubik
|
|
|
304
305
|
|
|
305
306
|
def clip(text, limit)
|
|
306
307
|
value = Rubik::Security::Redactor.redact(text.to_s)
|
|
307
|
-
|
|
308
|
+
Rubik::Tools::Truncator.clip(value, limit)
|
|
308
309
|
end
|
|
309
310
|
|
|
310
311
|
def config_get(config, key, default = nil)
|