rubik 0.9.1 → 0.10.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 (107) hide show
  1. checksums.yaml +4 -4
  2. data/ATTRIBUTION.md +1 -1
  3. data/CHANGELOG.md +143 -1
  4. data/lib/rubik/adapter/base.rb +2 -1
  5. data/lib/rubik/adapter/process.rb +28 -67
  6. data/lib/rubik/benchmark/vakanuvis_adoption.rb +10 -3
  7. data/lib/rubik/buffer/apply_contract.rb +3 -3
  8. data/lib/rubik/buffer/apply_transaction.rb +165 -0
  9. data/lib/rubik/buffer/manager.rb +26 -120
  10. data/lib/rubik/config/deep_ops.rb +4 -1
  11. data/lib/rubik/config/defaults.rb +6 -3
  12. data/lib/rubik/config/schema.rb +8 -0
  13. data/lib/rubik/config/secret_policy.rb +197 -0
  14. data/lib/rubik/config.rb +11 -0
  15. data/lib/rubik/diagnostics/collector.rb +0 -9
  16. data/lib/rubik/errors.rb +15 -0
  17. data/lib/rubik/event_bus.rb +2 -1
  18. data/lib/rubik/kernel/dispatcher.rb +12 -7
  19. data/lib/rubik/kernel/unit.rb +4 -1
  20. data/lib/rubik/llm/registry.rb +12 -9
  21. data/lib/rubik/llm/router.rb +2 -5
  22. data/lib/rubik/log.rb +21 -0
  23. data/lib/rubik/lsp/client.rb +77 -273
  24. data/lib/rubik/lsp/manager.rb +14 -10
  25. data/lib/rubik/lsp/transport.rb +365 -0
  26. data/lib/rubik/mcp/boot_lifecycle.rb +6 -2
  27. data/lib/rubik/mcp/boot_run.rb +190 -0
  28. data/lib/rubik/mcp/manager.rb +40 -163
  29. data/lib/rubik/mcp/transport/stdio.rb +4 -1
  30. data/lib/rubik/orchestrator/auto_apply.rb +4 -3
  31. data/lib/rubik/orchestrator/continuation_manager.rb +3 -22
  32. data/lib/rubik/orchestrator/goal_session.rb +53 -39
  33. data/lib/rubik/orchestrator/loop.rb +28 -47
  34. data/lib/rubik/orchestrator/maestro_gate.rb +5 -7
  35. data/lib/rubik/orchestrator/provider_recovery.rb +4 -2
  36. data/lib/rubik/orchestrator/provider_resolver.rb +4 -2
  37. data/lib/rubik/orchestrator/resume_window.rb +96 -0
  38. data/lib/rubik/orchestrator/shell_deps.rb +16 -0
  39. data/lib/rubik/orchestrator/stream_manager.rb +2 -1
  40. data/lib/rubik/orchestrator/subagent/deferred_spec.rb +4 -1
  41. data/lib/rubik/orchestrator/subagent/instance.rb +7 -12
  42. data/lib/rubik/orchestrator/subagent/lifecycle.rb +3 -1
  43. data/lib/rubik/orchestrator/subagent/questioner.rb +3 -1
  44. data/lib/rubik/orchestrator/subagent/reaper.rb +3 -5
  45. data/lib/rubik/orchestrator/subagent/resilience.rb +4 -2
  46. data/lib/rubik/orchestrator/subagent/result_archive.rb +0 -4
  47. data/lib/rubik/orchestrator/subagent/run_cycle.rb +2 -7
  48. data/lib/rubik/orchestrator/subagent/spawn_transaction.rb +11 -2
  49. data/lib/rubik/orchestrator/subagent/step_runner.rb +10 -2
  50. data/lib/rubik/orchestrator/subagent/type_definition.rb +0 -4
  51. data/lib/rubik/orchestrator/tool_timeout.rb +121 -1
  52. data/lib/rubik/platform/io_drain.rb +2 -1
  53. data/lib/rubik/platform/process.rb +144 -54
  54. data/lib/rubik/platform.rb +2 -1
  55. data/lib/rubik/plugin/manager.rb +2 -1
  56. data/lib/rubik/repl/commands/agent_context.rb +8 -7
  57. data/lib/rubik/repl/commands/agent_execution.rb +13 -32
  58. data/lib/rubik/repl/commands/agent_models.rb +4 -3
  59. data/lib/rubik/repl/commands/agent_providers.rb +43 -2
  60. data/lib/rubik/repl/commands/base.rb +47 -2
  61. data/lib/rubik/repl/commands/buffer.rb +5 -4
  62. data/lib/rubik/repl/commands/lsp.rb +2 -1
  63. data/lib/rubik/repl/commands/pruner.rb +2 -1
  64. data/lib/rubik/repl/commands/secrets.rb +151 -0
  65. data/lib/rubik/repl/commands/workspace.rb +60 -150
  66. data/lib/rubik/repl/commands/workspace_approval.rb +209 -0
  67. data/lib/rubik/repl/config_wiring.rb +3 -3
  68. data/lib/rubik/repl/hooks.rb +2 -1
  69. data/lib/rubik/repl/input_execution.rb +158 -76
  70. data/lib/rubik/repl/input_loop.rb +2 -1
  71. data/lib/rubik/repl/lifecycle.rb +59 -209
  72. data/lib/rubik/repl/notice_router.rb +319 -0
  73. data/lib/rubik/repl/paste_support.rb +3 -1
  74. data/lib/rubik/repl/presentation.rb +5 -3
  75. data/lib/rubik/repl/pruner/gate.rb +3 -1
  76. data/lib/rubik/repl/pruner/harness.rb +2 -1
  77. data/lib/rubik/repl/shell.rb +4 -3
  78. data/lib/rubik/repl/turn_recorder.rb +6 -5
  79. data/lib/rubik/runtime/discovery.rb +3 -2
  80. data/lib/rubik/runtime/loop_service.rb +4 -3
  81. data/lib/rubik/runtime/manifest_store.rb +9 -1
  82. data/lib/rubik/runtime/overlay_guard.rb +127 -0
  83. data/lib/rubik/runtime/overlay_storage.rb +92 -146
  84. data/lib/rubik/runtime/task_manager.rb +64 -25
  85. data/lib/rubik/sandbox/driver/docker.rb +5 -1
  86. data/lib/rubik/sandbox/runner.rb +16 -15
  87. data/lib/rubik/security/command_gate.rb +117 -93
  88. data/lib/rubik/security/guard.rb +6 -2
  89. data/lib/rubik/security/secret_store.rb +463 -0
  90. data/lib/rubik/security/synthesis_gate.rb +8 -11
  91. data/lib/rubik/session/manager.rb +7 -1
  92. data/lib/rubik/skills/manager.rb +2 -3
  93. data/lib/rubik/storage/search.rb +49 -0
  94. data/lib/rubik/storage/store.rb +13 -20
  95. data/lib/rubik/storage/vakanuvis/harness.rb +2 -3
  96. data/lib/rubik/tools/base.rb +22 -0
  97. data/lib/rubik/tools/builtins/files.rb +3 -15
  98. data/lib/rubik/tools/builtins/grep.rb +1 -6
  99. data/lib/rubik/tools/builtins/lifecycle.rb +6 -5
  100. data/lib/rubik/tools/lifecycle_rollbacks.rb +14 -1
  101. data/lib/rubik/tools/truncator.rb +48 -36
  102. data/lib/rubik/ui/banner.rb +4 -3
  103. data/lib/rubik/ui/spinner.rb +3 -1
  104. data/lib/rubik/ui/statusline.rb +6 -5
  105. data/lib/rubik/version.rb +1 -1
  106. data/lib/rubik.rb +1 -2
  107. metadata +13 -1
@@ -2,6 +2,8 @@
2
2
 
3
3
  require "monitor"
4
4
  require_relative "boot_lifecycle"
5
+ require_relative "../storage/layout"
6
+ require_relative "boot_run"
5
7
  require_relative "client"
6
8
  require_relative "proxy_tool"
7
9
  require_relative "errors"
@@ -59,7 +61,7 @@ module Rubik
59
61
  def enabled?
60
62
  return true unless @config
61
63
 
62
- @config.fetch("mcp.enabled", true) != false
64
+ Rubik::Storage::Layout.config_get(@config, "mcp.enabled", true) != false
63
65
  end
64
66
 
65
67
  # Returns {ok:, tools:} — the config persist outcome plus the registered
@@ -338,181 +340,56 @@ module Rubik
338
340
 
339
341
  private
340
342
 
341
- # Config boot, decomposed into the named phases over the concurrency
342
- # boundary so N servers' connect handshakes (spawn + initialize +
343
- # tools/list — the slow I/O) overlap while every observable state
344
- # change stays sequential in config order. Boot wall clock goes
345
- # sum(per-server) → max(per-server); one hung server no longer delays
346
- # the rest. Pure orchestration below: each phase is a private method,
347
- # moved verbatim from the former single body (zero logic change).
343
+ # Config boot, decomposed into a BootRun (boot_run.rb): the five named
344
+ # boot phases moved verbatim onto a private run object that owns
345
+ # entries / connected / outcomes / boot_epoch, replacing the former
346
+ # side-channel parameters. N servers' connect handshakes (spawn +
347
+ # initialize + tools/list — the slow I/O) overlap while every
348
+ # observable state change stays sequential in config order (sum → max
349
+ # wall clock). This method only parses the config and opens the run.
348
350
  def perform_load_from_config(cfg = nil)
349
351
  target_config = cfg || @config
350
352
  return unless target_config
351
353
 
352
- mcp_enabled = target_config.fetch("mcp.enabled", true) != false
353
- servers_cfg = target_config.fetch("mcp.servers", {})
354
+ mcp_enabled = Rubik::Storage::Layout.config_get(target_config, "mcp.enabled", true) != false
355
+ servers_cfg = Rubik::Storage::Layout.config_get(target_config, "mcp.servers", {})
354
356
  return unless servers_cfg.is_a?(Hash)
355
357
 
356
- # Boot epoch (review round): :connecting marks are tagged with a
357
- # per-invocation identity so a wedged older boot's failure branch or
358
- # ensure sweep can never downgrade a newer boot's fresh mark.
359
- boot_epoch = Object.new
360
- entries = register_config_servers(servers_cfg, mcp_enabled, boot_epoch)
361
-
362
- # Phase 1 deliberately did no context wiring, so stopping the client
363
- # is the ONLY cleanup an unapplied prepared slot owes — no orphaned
364
- # child processes, even when an interrupt lands mid-boot. One ensure
365
- # spans both post-registration phases.
366
- connected = ::Array.new(entries.size)
367
- outcomes = {}
368
- begin
369
- connect_fanout(entries, connected)
370
- apply_connected_slots(entries, connected, boot_epoch, outcomes)
371
- ensure
372
- stop_unapplied_clients(entries, connected, outcomes)
373
- fail_orphaned_connecting_marks(entries, boot_epoch)
374
- end
375
- nil
358
+ BootRun.new(self, servers_cfg, mcp_enabled).run
376
359
  end
377
360
 
378
- # Phase 0 (sequential, config order): registration still goes
379
- # through add_server — subclasses and plugins wrap that seam, and a
380
- # broken definition must fail exactly as before (logged, skipped,
381
- # not half-registered). auto_start is deliberately false here: the
382
- # connect half moved to the fan-out. Ends each auto-start candidate
383
- # with the phase-0 claim (D5) and returns the entries to boot.
384
- def register_config_servers(servers_cfg, mcp_enabled, boot_epoch)
385
- entries = []
386
- servers_cfg.each do |sname, sdefn|
387
- next unless sdefn.is_a?(Hash)
388
-
389
- auto_start = mcp_enabled && (sdefn.fetch("enabled", true) != false)
390
- begin
391
- add_server(sname, sdefn, auto_start: false, persist: nil)
392
- rescue StandardError => e
393
- # ENSURE-LOG (G3 round-1): one broken server config used to
394
- # vanish behind an ENV["RUBIK_DEBUG"] gate; a misconfigured
395
- # server must surface without debug mode.
396
- Rubik::Log.warn(:mcp, "failed to load MCP server '#{sname}' (#{e.class}: #{e.message})")
397
- emit_mcp_event(:mcp_server_failed, :err, sname.to_s, error: e.message)
398
- next
399
- end
400
- next unless auto_start
401
-
402
- name_str = sname.to_s
403
- # Phase-0 claim (D5): check+mark in ONE monitor hold — a user
404
- # enable/disable/remove that races the boot reads a definite
405
- # state, and phase 2's gate below can never miss a window.
406
- entries << [name_str, sdefn.transform_keys(&:to_s)] unless claim_boot_slot!(name_str, boot_epoch)
407
- end
408
- entries
409
- end
410
-
411
- # Phase 1 (fan-out): pure I/O connects. Slots are captured by SIDE
412
- # EFFECT inside the item blocks: when an Exception-level error (a
413
- # boot interrupt) kills .map before it returns, the assignment below
414
- # never happens — a value-only `connected` would leave the ensure
415
- # blind to every successfully-started client. Hence the pre-built
416
- # array passed in rather than a returned value.
417
- def connect_fanout(entries, connected)
418
- return if entries.empty?
419
-
420
- Rubik::Concurrency.map(entries.each_with_index.to_a) do |(name_str, parsed_defn), index|
421
- connected[index] = { ok: true, **connect_server(name_str, parsed_defn) }
422
- rescue StandardError => e
423
- connected[index] = { ok: false, error: e }
424
- end
425
- end
426
-
427
- # Phase 2 (sequential, config order): apply state; identical
428
- # per-server warning on either phase's failure. Outcomes ledger is an
429
- # explicit atom map (index -> :applied | :failed; absence = skipped or
430
- # never ran — exactly what owes_stop? reads).
431
- def apply_connected_slots(entries, connected, boot_epoch, outcomes)
432
- entries.each_with_index do |(name_str, parsed_defn), index|
433
- slot = connected[index]
434
- next unless slot # never connected (interrupt during phase 1)
435
-
436
- if slot[:ok]
437
- begin
438
- outcome = @monitor.synchronize do
439
- # Single race gate (D5), checked at apply time under the
440
- # monitor: a disable/remove/enable during boot wins over
441
- # the boot's own apply, and a stop_all skips it entirely.
442
- # Epoch-complete gate: this boot may only apply into the
443
- # slot its own phase-0 claim marked, so a user decision
444
- # that moved the slot or a newer boot's fresh mark wins.
445
- # In the synchronous path nothing can interleave, so the
446
- # guard is provably inert there.
447
- if @stopped || @statuses[name_str] != :connecting || !@boot_marks[name_str].equal?(boot_epoch)
448
- :skipped
449
- else
450
- apply_connected_server(name_str, parsed_defn, client: slot[:client], tools: slot[:tools])
451
- # Post-apply revalidation under the boot actor: a no-op
452
- # when apply already landed :active.
453
- transition_server!(name_str, :active, epoch: boot_epoch)
454
- :applied
455
- end
456
- end
457
- outcomes[index] = :applied if outcome == :applied
458
- emit_mcp_event(:mcp_server_loaded, :info, name_str, tools: (@tools[name_str] || []).size) if outcome == :applied
459
- rescue StandardError => e
460
- # ENSURE-LOG (G3 round-1): one broken server config used to
461
- # vanish behind an ENV["RUBIK_DEBUG"] gate; a misconfigured
462
- # server must surface without debug mode. apply's own
463
- # rollback already set :failed and stopped its client via
464
- # the context drain; :failed marks the slot so the ensure
465
- # never double-stops it.
466
- outcomes[index] = :failed
467
- Rubik::Log.warn(:mcp, "failed to load MCP server '#{name_str}' (#{e.class}: #{e.message})")
468
- emit_mcp_event(:mcp_server_failed, :err, name_str, error: e.message)
469
- end
361
+ # BootRun friend seam (boot_run.rb): the D5 race gate, one monitor
362
+ # hold deciding :skipped vs :applied. Moved verbatim — the hold
363
+ # boundary, the @stopped/@statuses/@boot_marks epoch gate and the
364
+ # guarded writes inside are exactly the former inline block; BootRun
365
+ # only receives the decision.
366
+ def boot_apply_gate(name_str, parsed_defn, boot_epoch, client:, tools:)
367
+ @monitor.synchronize do
368
+ # Single race gate (D5), checked at apply time under the
369
+ # monitor: a disable/remove/enable during boot wins over
370
+ # the boot's own apply, and a stop_all skips it entirely.
371
+ # Epoch-complete gate: this boot may only apply into the
372
+ # slot its own phase-0 claim marked, so a user decision
373
+ # that moved the slot or a newer boot's fresh mark wins.
374
+ # In the synchronous path nothing can interleave, so the
375
+ # guard is provably inert there.
376
+ if @stopped || @statuses[name_str] != :connecting || !@boot_marks[name_str].equal?(boot_epoch)
377
+ :skipped
470
378
  else
471
- # Only our own epoch's mark may flip to :failed — a user
472
- # disable/remove during the handshake, or a newer boot's fresh
473
- # mark, must win over this boot's connect failure (D5). The
474
- # epoch gate and flip happen in the same monitor hold inside
475
- # transition_server!.
476
- transition_server!(name_str, :failed, epoch: boot_epoch)
477
- error = slot[:error]
478
- Rubik::Log.warn(:mcp, "failed to load MCP server '#{name_str}' (#{error.class}: #{error.message})")
479
- emit_mcp_event(:mcp_server_failed, :err, name_str, error: error.message)
480
- end
481
- end
482
- end
483
-
484
- # Ensure part 1: stop every prepared client that did not end up
485
- # registered: a failed apply already rolled its own client back via
486
- # the context drain, while a never-applied one (interrupt between
487
- # phases) owes a stop here. A :skipped slot also owes a stop —
488
- # skipping the APPLY must not orphan its prepared child process (that
489
- # is the exact leak D10 closed for handshakes). owes_stop? is the
490
- # structural form of that rule: skipped and never-ran slots owe.
491
- def stop_unapplied_clients(entries, connected, outcomes)
492
- entries.each_with_index do |(name_str, _defn), index|
493
- slot = connected[index]
494
- next if !slot.is_a?(Hash) || !slot[:client] || !BootLifecycle.owes_stop?(outcomes[index])
495
-
496
- registered = @monitor.synchronize { @clients[name_str] }
497
- next if registered.equal?(slot[:client])
498
-
499
- begin
500
- slot[:client].stop
501
- rescue StandardError => e
502
- Rubik::Log.warn(:mcp, "failed to stop unapplied MCP server '#{name_str}' (#{e.class}: #{e.message})")
379
+ apply_connected_server(name_str, parsed_defn, client: client, tools: tools)
380
+ # Post-apply revalidation under the boot actor: a no-op
381
+ # when apply already landed :active.
382
+ transition_server!(name_str, :active, epoch: boot_epoch)
383
+ :applied
503
384
  end
504
385
  end
505
386
  end
506
387
 
507
- # Ensure part 2 — terminal state for boot entries that never reached
508
- # apply (D6): anything still :connecting failed to boot; user-chosen
509
- # values (:disabled, :active, deleted-by-remove) are left untouched.
510
- # The epoch check inside transition_server! keeps an older wedged
511
- # boot's sweep from downgrading a newer boot's fresh mark.
512
- def fail_orphaned_connecting_marks(entries, boot_epoch)
513
- entries.each do |(name_str, _defn)|
514
- transition_server!(name_str, :failed, epoch: boot_epoch)
515
- end
388
+ # BootRun friend seam: the advisory @tools count read for the
389
+ # :mcp_server_loaded event — the same unguarded read the inline phase
390
+ # performed (observability only, never a state decision).
391
+ def tool_count(name_str)
392
+ (@tools[name_str] || []).size
516
393
  end
517
394
 
518
395
  public
@@ -159,6 +159,9 @@ module Rubik
159
159
 
160
160
  def close
161
161
  child_died = false
162
+ # Capture before @wait_thr is nil'd below: the child-died diagnostic
163
+ # must still report WHICH server process failed to start.
164
+ exited_pid = @wait_thr&.pid
162
165
  @mutex.synchronize do
163
166
  return if @closed
164
167
 
@@ -226,7 +229,7 @@ module Rubik
226
229
 
227
230
  if child_died
228
231
  hint = stderr_tail.last(5).join(" | ")[0, 512]
229
- Rubik::Log.warn(:mcp, "MCP child process (pid #{pid}) had already exited; recent stderr: #{hint}") unless hint.empty?
232
+ Rubik::Log.warn(:mcp, "MCP child process (pid #{exited_pid}) had already exited; recent stderr: #{hint}") unless hint.empty?
230
233
  end
231
234
 
232
235
  @mutex.synchronize do
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "subagent/notices"
4
+ require_relative "../storage/layout"
4
5
 
5
6
  module Rubik
6
7
  module Orchestrator
@@ -58,7 +59,7 @@ module Rubik
58
59
  # overrides config resolution entirely — the StepExecutor injection
59
60
  # seam (its tests pass explicit modes positionally).
60
61
  def apply?(config, trigger:, subagent: false, tool: nil, mode: nil)
61
- return false if config.respond_to?(:fetch) && config.fetch("buffer.model_can_apply", true) == false
62
+ return false if Rubik::Storage::Layout.config_get(config, "buffer.model_can_apply", true) == false
62
63
 
63
64
  return false if trigger == :pre_execution && !tool.nil? && !test_class_tool?(tool)
64
65
 
@@ -146,11 +147,11 @@ module Rubik
146
147
  # -- one defensive spelling each (replaced eight) -------------------
147
148
 
148
149
  def mode(config)
149
- config.respond_to?(:fetch) ? config.fetch(MODE_KEY, DEFAULT_MODE).to_s.downcase : DEFAULT_MODE
150
+ Rubik::Storage::Layout.config_get(config, MODE_KEY, DEFAULT_MODE).to_s.downcase
150
151
  end
151
152
 
152
153
  def subagent_flag_on?(config)
153
- config.respond_to?(:fetch) ? config.fetch(FLAG_KEY, DEFAULT_FLAG) == true : DEFAULT_FLAG
154
+ Rubik::Storage::Layout.config_get(config, FLAG_KEY, DEFAULT_FLAG) == true
154
155
  end
155
156
 
156
157
  def test_class_tool?(canonical_name)
@@ -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 Orchestrator
5
7
  # Manages auto-continuation when an LLM response is truncated due to
@@ -131,28 +133,7 @@ module Rubik
131
133
  private
132
134
 
133
135
  def safe_config(key, default)
134
- return default unless @config
135
-
136
- if @config.respond_to?(:fetch)
137
- begin
138
- val = @config.fetch(key)
139
- return val unless val.nil?
140
- rescue KeyError, ArgumentError
141
- nil
142
- end
143
- end
144
-
145
- if key.include?(".") && @config.respond_to?(:dig)
146
- val = @config.dig(*key.split("."))
147
- return val unless val.nil?
148
- end
149
-
150
- if @config.respond_to?(:[])
151
- val = @config[key]
152
- return val unless val.nil?
153
- end
154
-
155
- default
136
+ Rubik::Storage::Layout.config_get(@config, key, default)
156
137
  rescue KeyError, TypeError, NoMethodError
157
138
  default
158
139
  end
@@ -4,6 +4,7 @@ require "securerandom"
4
4
  require "time"
5
5
 
6
6
  require_relative "../log"
7
+ require_relative "../storage/layout"
7
8
  require_relative "../platform"
8
9
  require_relative "goal_state"
9
10
  require_relative "goal_registry"
@@ -24,8 +25,8 @@ module Rubik
24
25
  # GoalState + Σ ledger + registry provide discipline, the
25
26
  # honest-continuity output strings, the documented ordering
26
27
  # contracts (ledger_id-before-suspend!, suspend_stamp_meta
27
- # schema), and the single goal-shaped orchestrator-loop
28
- # stanza (build_goal_orchestrator)
28
+ # schema), the shared resume tail (resume_drive) and the
29
+ # goal-shaped orchestrator-loop stanza (build_goal_orchestrator)
29
30
  # leaves : command argument parsing and usage rendering
30
31
  # (REPL::Commands::AgentExecution), the Loop machinery
31
32
  # itself (Loop/GoalWait), and input_execution's streaming
@@ -48,7 +49,7 @@ module Rubik
48
49
 
49
50
  def execute_goal(ctx, goal_text, custom_steps)
50
51
  ctx.recorder&.record_user_turn("!goal #{goal_text}")
51
- goal_steps = custom_steps || ctx.config.fetch("agent.goal_max_steps", 100).to_i
52
+ goal_steps = custom_steps || Rubik::Storage::Layout.config_get(ctx.config, "agent.goal_max_steps", 100).to_i
52
53
  routed = ctx.router.route(task_type: :goal, prompt: goal_text)
53
54
  ctx.runtime_manager.provide(:llm_client, routed[:provider]) if routed[:provider]
54
55
 
@@ -196,7 +197,7 @@ module Rubik
196
197
  # route_subagent_notice) — soruya beklerken gelen subagent
197
198
  # olayları loop inbox'a girer ve devam adımında boşaltılır.
198
199
  auto_extensions = 0
199
- max_auto = ctx.config.fetch("agent.goal_auto_continue_limit", 0).to_i
200
+ max_auto = Rubik::Storage::Layout.config_get(ctx.config, "agent.goal_auto_continue_limit", 0).to_i
200
201
  # Yapılandırılmış neden (loop.rb terminali): insan-okur string
201
202
  # yalnız gösterim içindir — otomasyon prozu parse etmesin.
202
203
  while !res[:ok] && res[:reason] == :budget_exhausted
@@ -209,7 +210,7 @@ module Rubik
209
210
  next
210
211
  end
211
212
 
212
- break unless ctx.config.fetch("agent.ask_continue_on_limit", true)
213
+ break unless Rubik::Storage::Layout.config_get(ctx.config, "agent.ask_continue_on_limit", true)
213
214
 
214
215
  ctx.out.puts "\n⚠️ [Rubik::Goal] #{res[:error]}"
215
216
  ans = ctx.ask_yes_no(" [Rubik::Goal] +20 adım ile devam edilsin mi?", default: "n")
@@ -273,27 +274,21 @@ module Rubik
273
274
 
274
275
  def resume_in_process(ctx, entry)
275
276
  ctx.recorder&.record_user_turn("!goal resume")
277
+ # Kaynaklama (issue #454): canlı girdiden; resume! geçişi (SUSPENDED → RUNNING) kaynaklamanın parçası.
276
278
  goal_state = entry.goal_state
277
279
  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
280
  goal_state.resume!
282
281
  ctx.out.puts "[Rubik::Goal] Resuming '#{entry.goal_text}' (attempt #{entry.attempt + 1}, " \
283
282
  "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
- })
283
+ # Dürüst süreklilik: alt ajan konuşmaları süreç-içi resume'da yaşar — çapraz-süreç
284
+ # yoldaki tek cümlelik uyarı burada YOKTUR; ortak kuyruk resume_drive'da.
285
+ resume_drive(ctx, orchestrator: entry.loop, goal_state: goal_state, ledger: goal_ledger,
286
+ goal_text: entry.goal_text, goal_id: entry.goal_id,
287
+ start: lambda { |loop_inst|
288
+ loop_inst.resume!(reason: entry.reason,
289
+ suspended_at: entry.suspended_at,
290
+ attempt: entry.attempt)
291
+ })
297
292
  end
298
293
 
299
294
  def resume_cross_process(ctx)
@@ -323,17 +318,18 @@ module Rubik
323
318
 
324
319
  meta = ledger.suspend_meta || {}
325
320
  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
321
+ goal_steps = meta["max_steps"].to_i.positive? ? meta["max_steps"].to_i : Rubik::Storage::Layout.config_get(ctx.config, "agent.goal_max_steps", 100).to_i
327
322
  goal_state = Rubik::Orchestrator::GoalState.new(event_bus: ctx.event_bus)
328
323
  goal_state.start!(goal_text, goal_steps)
329
324
  goal_state.restore_counters!(steps: meta["steps"], max_steps: goal_steps,
330
325
  extensions: meta["extensions"], tokens: meta["tokens"])
331
326
  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
327
 
335
328
  routed = ctx.router.route(task_type: :goal, prompt: goal_text)
336
329
  ctx.runtime_manager.provide(:llm_client, routed[:provider]) if routed[:provider]
330
+ # Kaynaklama (issue #454): döngü build_goal_orchestrator ile yeniden
331
+ # kurulur — canlı Loop sürecle öldü (bilinçli asimetri; süreç-içi
332
+ # yolda entry.loop kullanılır).
337
333
  orchestrator = build_goal_orchestrator(ctx, goal_state: goal_state, routed: routed, steps: goal_steps)
338
334
 
339
335
  ctx.out.puts "[Rubik::Goal] Cross-process resume of '#{goal_text}' (attempt #{meta['attempt'].to_i})..."
@@ -341,22 +337,41 @@ module Rubik
341
337
  # konuşmaları süreçle öldü; disk etkileri ve session kaydı yaşar.
342
338
  ctx.out.puts " Subagent conversations did not survive the process restart — their disk " \
343
339
  "effects and the session record have."
344
- ledger.unsuspend!
340
+ resume_drive(ctx, orchestrator: orchestrator, goal_state: goal_state, ledger: ledger,
341
+ goal_text: goal_text,
342
+ goal_id: meta["goal_id"].to_s.empty? ? row.id : meta["goal_id"],
343
+ start: lambda { |loop_inst|
344
+ loop_inst.resume_from(goal_text: goal_text, ledger: ledger,
345
+ reason: meta["reason"].to_s,
346
+ suspended_at: parse_suspended_at(meta["suspended_at"]),
347
+ attempt: meta["attempt"].to_i,
348
+ counters: { steps: meta["steps"], max_steps: goal_steps,
349
+ tokens: meta["tokens"] })
350
+ })
351
+ end
352
+
353
+ # Resume ortak kuyruğu (issue #454): suspend_stamp_meta'nın resume
354
+ # tarafındaki aynası — coeffect sağlama disiplini (GOAL_STATE +
355
+ # sağlanan GOAL_LEDGER), Σ unsuspend!, nötr kayıtçı çifti, pruner
356
+ # apply sınırı, tek drive_goal_turn stanza'sı: "resume hangi
357
+ # coeffect'leri sağlar?" sorusunun TEK cevabı. Bilinçli asimetri
358
+ # arayan tarafta kalır (erken birleştirme yok): kaynaklama, dürüst
359
+ # süreklilik cümleleri ve döngü — süreç-içi yolda canlı entry.loop,
360
+ # çapraz-süreç yolda build_goal_orchestrator; start callable'ı yolu
361
+ # seçer (loop.resume! vs loop.resume_from).
362
+ def resume_drive(ctx, orchestrator:, goal_state:, ledger:, goal_text:, goal_id:, start:)
363
+ ctx.runtime_manager.provide(Rubik::Coeffects::GOAL_STATE, goal_state)
364
+ ctx.runtime_manager.provide(Rubik::Coeffects::GOAL_LEDGER, ledger) if ledger
365
+ ledger&.unsuspend!
345
366
  record_pair = build_goal_record_pair(ctx, goal_text)
367
+ # Pruner apply seam: hedef döngüsü de aynı sınırda tohumlanır —
368
+ # aşamalı budama planı varsa goal promptundan ÖNCE uygulanır.
346
369
  ctx.apply_staged_prune_plan!
347
370
  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
- })
371
+ goal_ledger: ledger, goal_text: goal_text, goal_id: goal_id,
372
+ record_pair: record_pair, start: start)
359
373
  end
374
+ private_class_method :resume_drive
360
375
 
361
376
  # !goal list (issue #106 Faz 2a): store'daki status == "suspended"
362
377
  # Σ satırları — özetler zaten status taşıyor (Store::Summary).
@@ -397,8 +412,7 @@ module Rubik
397
412
  end
398
413
 
399
414
  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
415
+ Rubik::Coeffects.get(ctx.runtime_manager&.context, Rubik::Coeffects::GOAL_REGISTRY)&.fetch(goal_id)&.attempt.to_i
402
416
  end
403
417
 
404
418
  # Oturum kaydı coeffect'i: ilk askıda provide edilir (provide-swap
@@ -464,7 +478,7 @@ module Rubik
464
478
  # warn_at_ratio) and input_execution (streaming on_step) keep their
465
479
  # materially different stanzas inline at their own sites.
466
480
  def build_goal_orchestrator(ctx, goal_state:, routed:, steps:)
467
- warn_ratio = ctx.config.fetch("agent.warn_at_ratio", 0.75).to_f
481
+ warn_ratio = Rubik::Storage::Layout.config_get(ctx.config, "agent.warn_at_ratio", 0.75).to_f
468
482
  ctx.orchestrator_loop(
469
483
  provider: routed[:provider],
470
484
  model: routed[:model],
@@ -12,6 +12,8 @@ require_relative "provider_resolver"
12
12
  require_relative "provider_recovery"
13
13
  require_relative "continuation_manager"
14
14
  require_relative "goal_wait"
15
+ require_relative "resume_window"
16
+ require_relative "../storage/layout"
15
17
  require_relative "subagent_notice_inbox"
16
18
  require_relative "turn_executor"
17
19
  require_relative "turn_executor/user_channel"
@@ -21,8 +23,8 @@ require_relative "subagent/notices"
21
23
  module Rubik
22
24
  module Orchestrator
23
25
  class Loop
24
- attr_accessor :history, :invalid_tool_count, :last_turn_streamed, :context_warning_emitted
25
- attr_reader :max_steps, :step_count, :model, :total_tokens, :warn_at_ratio, :runtime_manager, :loop_context, :context_limit, :max_output_tokens, :config
26
+ attr_accessor :history, :invalid_tool_count, :last_turn_streamed, :context_warning_emitted, :loop_context
27
+ attr_reader :max_steps, :step_count, :model, :total_tokens, :warn_at_ratio, :runtime_manager, :context_limit, :max_output_tokens, :config
26
28
  # Collaborator-facing state (Plan 54 D-5): loop state physically stays on Loop;
27
29
  # extracted collaborators reach it through these accessors.
28
30
  attr_reader :provider, :on_step, :tool_registry, :shell, :buffer_manager, :lsp_manager, :step_executor,
@@ -54,7 +56,7 @@ module Rubik
54
56
  @root_dir = File.expand_path(shell&.buffer_manager&.root_dir || Dir.pwd)
55
57
  @runtime_manager = shell&.runtime_manager
56
58
  @context_limit = context_limit || 32_768
57
- @max_output_tokens = (max_output_tokens || (@config.respond_to?(:fetch) ? @config.fetch("llm.default_max_output_tokens", 4_096) : 4_096)).to_i
59
+ @max_output_tokens = (max_output_tokens || Rubik::Storage::Layout.config_get(@config, "llm.default_max_output_tokens", 4_096)).to_i
58
60
  @loop_context = nil
59
61
  @step_count = 0
60
62
  @history = []
@@ -108,6 +110,12 @@ module Rubik
108
110
  def goal_wait = (@goal_wait ||= GoalWait.new(@shell_deps))
109
111
  def continuation_manager = (@continuation_manager ||= ContinuationManager.new(config: @config))
110
112
 
113
+ # Loop-side resume window collaborator (issue #475): owns the
114
+ # ctx.extend lifecycle, the cross-process history prefix and the
115
+ # goal_resumed marker. Lazy like goal_wait — Class#allocate test
116
+ # doubles skip initialize.
117
+ def resume_window = (@resume_window ||= ResumeWindow.new(@shell_deps))
118
+
111
119
  # Agent-turn-executor plan: response processing is shared with the
112
120
  # subagent channel through TurnExecutor; Loop supplies the
113
121
  # user-channel adapter. Built lazily on first use, NOT in
@@ -199,18 +207,17 @@ module Rubik
199
207
 
200
208
  # Süreç-içi resume (Faz 1): hayatta kalan Loop örneğinde history
201
209
  # prefix'i nesne-özdeş kalır, yalnızca goal_resumed imzası eklenir.
202
- # run()'ın ensure'ı per-run alt bağlamı (loop_context) imha etmiş
203
- # olduğu için resume taze bir ctx.extend ile yeniden kurar; askılı
204
- # koşunun ESKİ alt bağlamı önce LIFO disipliniyle imha edilir —
205
- # yoksa her suspend/resume döngüsü ölü bir çocuk sızdırır (§6).
210
+ # Sub-context ve imza düzeni ResumeWindow işbirlikçisindedir (issue
211
+ # #475): resume_window.reopen_context! askılı koşunun ESKİ alt
212
+ # bağlamını LIFO disipliniyle imha eder, sonra taze bir ctx.extend
213
+ # kurar — yoksa her suspend/resume döngüsü ölü bir çocuk sızdırır (§6).
206
214
  def resume!(reason:, suspended_at: nil, attempt: 1)
207
- @loop_context&.dispose
208
- @loop_context = @runtime_manager&.context&.extend
209
- append_resume_marker!(reason: reason, suspended_at: suspended_at, attempt: attempt)
215
+ resume_window.reopen_context!
210
216
  begin
217
+ resume_window.stamp_resume_marker!(reason: reason, suspended_at: suspended_at, attempt: attempt)
211
218
  execute_steps(opts: resume_request_opts)
212
219
  ensure
213
- @loop_context&.dispose
220
+ resume_window.close_context!
214
221
  end
215
222
  end
216
223
 
@@ -223,16 +230,16 @@ module Rubik
223
230
  def resume_from(goal_text:, ledger:, reason:, suspended_at: nil, attempt: 1, counters: {})
224
231
  @goal_mode = true
225
232
  restore_resume_counters!(counters)
226
- @loop_context = @runtime_manager&.context&.extend
233
+ resume_window.open_context!
227
234
  begin
228
- @history << { role: "system", content: render_system_prompt(mode: :goal, plan_only: false, extra_context: nil) }
235
+ system_prompt = render_system_prompt(mode: :goal, plan_only: false, extra_context: nil)
236
+ resume_window.build_cross_process_prefix!(goal_text: goal_text, ledger: ledger,
237
+ system_prompt: system_prompt)
229
238
  @last_prompt_fingerprint = prompt_state_fingerprint(plan_only: false)
230
- @history << { role: "user", content: Rubik::Prompt::ContextBuilder.format_user_task(goal_text) }
231
- @history << { role: "user", content: ledger.to_xml }
232
- append_resume_marker!(reason: reason, suspended_at: suspended_at, attempt: attempt)
239
+ resume_window.stamp_resume_marker!(reason: reason, suspended_at: suspended_at, attempt: attempt)
233
240
  execute_steps(opts: resume_request_opts)
234
241
  ensure
235
- @loop_context&.dispose
242
+ resume_window.close_context!
236
243
  end
237
244
  end
238
245
 
@@ -247,9 +254,7 @@ module Rubik
247
254
  end
248
255
 
249
256
  def safe_config(key, default)
250
- return default unless @config.respond_to?(:fetch)
251
-
252
- @config.fetch(key, default) || default
257
+ Rubik::Storage::Layout.config_get(@config, key, default)
253
258
  rescue KeyError, TypeError, NoMethodError
254
259
  default
255
260
  end
@@ -322,33 +327,9 @@ module Rubik
322
327
  opts
323
328
  end
324
329
 
325
- # goal_resumed imza satırı (Faz 2a penceresinin son halkası): rol
326
- # "user" (EmergencyCompactor hard tier dokunmaz), tek-etiket
327
- # alıntı disiplini (ledger_row?/drift_row? moldu). downtime insan
328
- # okur biçimdedir; bilinemezse "unknown". reason Σ damgasıyla aynı
329
- # 300-karakter disiplinine tabidir — 5xx gövdeleri history'yi
330
- # şişirmesin.
331
- def append_resume_marker!(reason:, suspended_at:, attempt:)
332
- esc = Rubik::Platform.method(:xml_escape)
333
- @history << { role: "user", content: "<goal_resumed downtime=\"#{esc.call(format_downtime(suspended_at))}\" " \
334
- "reason=\"#{esc.call(reason.to_s.slice(0, 300))}\" attempt=\"#{attempt.to_i}\" " \
335
- "steps_done=\"#{@step_count}\" />" }
336
- end
337
-
338
- # saniye → "45s" / "4m 12s" / "1h 03m"; askı zamanı bilinmiyorsa
339
- # dürüst "unknown" (çapraz-süreç meta bozuksa). Negatif sapma
340
- # (saat kayması) 0'a kestirilir.
341
- def format_downtime(suspended_at)
342
- return "unknown" unless suspended_at.respond_to?(:to_i) && suspended_at.to_i.positive?
343
-
344
- secs = [(Time.now - suspended_at).to_i, 0].max
345
- mm, ss = secs.divmod(60)
346
- hh, mm = mm.divmod(60)
347
- return "#{hh}h #{mm.to_s.rjust(2, '0')}m" if hh.positive?
348
- return "#{mm}m #{ss.to_s.rjust(2, '0')}s" if mm.positive?
349
-
350
- "#{ss}s"
351
- end
330
+ # goal_resumed imza satırı ve sub-context düzeni ResumeWindow'da
331
+ # (issue #475); Loop yalnızca sayaç geri yükleme ve request-opts
332
+ # sözleşmelerini tutar.
352
333
 
353
334
  def restore_resume_counters!(counters)
354
335
  @step_count = counters[:steps].to_i