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
@@ -28,6 +28,11 @@ module Rubik
28
28
  attrs += %( updated_at="#{@updated_at.utc.iso8601}") if @updated_at
29
29
  body = []
30
30
  body << %( <objective>#{esc.call(@doc['objective'].to_s)}</objective>)
31
+ # Statik gramer sözlüğü (Ledger.schema_vocabulary — SSOT türetme):
32
+ # durum-bağımsız tek satır; pinli Σ satırına sabit maliyet, modele
33
+ # kullanım anının dibinde kalıcı öğretim ("yokluk, boşluk değil"
34
+ # kuralı koleksiyonlar içindir — sözlük koleksiyon değildir).
35
+ body << %( <vocabulary>#{esc.call(Ledger.schema_vocabulary)}</vocabulary>)
31
36
  tasks = @doc["tasks"].each_with_index.map do |task, idx|
32
37
  text = task["title"].to_s
33
38
  text += " — notes: #{task['notes']}" if task["notes"]
@@ -38,7 +43,7 @@ module Rubik
38
43
  end
39
44
  body << "<tasks>\n#{tasks.join("\n")}\n </tasks>" unless tasks.empty?
40
45
  findings = @doc["findings"].each_with_index.map do |f, idx|
41
- %( <finding id="#{esc.call(f['id'].to_s)}" source_step="#{f['source_step']}" index="#{idx}">#{esc.call(f['text'].to_s)}</finding>)
46
+ %( <finding id="#{esc.call(f['id'].to_s)}" source_step="#{esc.call(f['source_step'].to_s)}" index="#{idx}">#{esc.call(f['text'].to_s)}</finding>)
42
47
  end
43
48
  body << "<findings>\n#{findings.join("\n")}\n </findings>" unless findings.empty?
44
49
  decisions = @doc["decisions"].each_with_index.map do |dec, idx|
@@ -57,6 +57,7 @@ end
57
57
 
58
58
  require_relative "goal_ledger/patch"
59
59
  require_relative "goal_ledger/schema"
60
+ require_relative "goal_ledger/schema_vocabulary"
60
61
  require_relative "goal_ledger/validator"
61
62
  require_relative "goal_ledger/ledger"
62
63
  require_relative "goal_ledger/verify_spec"
@@ -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
@@ -37,7 +37,7 @@ module Rubik
37
37
  # review, Plan 87). warn keeps the failure visible on stderr;
38
38
  # ANSI stripping keeps LSP-server-controlled messages from
39
39
  # injecting terminal escape sequences (red-team E1).
40
- warn("LSP sync skipped: #{e.message.gsub(/\e\[[0-9;]*[A-Za-z]/, '')}")
40
+ Rubik::Log.warn(:lsp, "LSP sync skipped: #{e.message.gsub(/\e\[[0-9;]*[A-Za-z]/, '')}")
41
41
  tool_result
42
42
  end
43
43
 
@@ -2,6 +2,7 @@
2
2
 
3
3
  require_relative "../tools/catalog"
4
4
  require_relative "tool_history"
5
+ require_relative "../storage/layout"
5
6
 
6
7
  module Rubik
7
8
  module Orchestrator
@@ -29,14 +30,11 @@ module Rubik
29
30
  !["start"].include?((tool_args["action"] || tool_args[:action]).to_s.downcase.strip)
30
31
 
31
32
  # Kapıyı çalışma anında config'den oku (!config set ile operatör
32
- # aç/kapa mümkün). Gerçek Config dotted fetch'i çözer
33
- # ("subagents.maestro_gate"); düz Hash (test doubles) nested tutar —
34
- # dig fallback'i iki şekli de kapsar (dotted-key config gotchası).
33
+ # aç/kapa mümkün). config_get (Storage::Layout) gerçek Config'in
34
+ # dotted fetch'ini ve düz Hash'in nested (dig) şeklini tek evde
35
+ # çözer.
35
36
  cfg = @deps.shell&.config
36
- return true unless cfg.respond_to?(:fetch)
37
-
38
- raw = cfg.fetch("subagents.maestro_gate", nil)
39
- raw = cfg.dig("subagents", "maestro_gate") if raw.nil? && cfg.respond_to?(:dig)
37
+ raw = Rubik::Storage::Layout.config_get(cfg, "subagents.maestro_gate", nil)
40
38
  raw != false
41
39
  end
42
40
 
@@ -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
  # Deep module (Candidate 03): the ONE home for provider-call recovery
@@ -70,14 +72,14 @@ module Rubik
70
72
  # compaction call site: nil config, fetch-less objects, and null YAML
71
73
  # sections all collapse to {}. One spelling replaces five.
72
74
  def compaction_config(config)
73
- cfg = config.respond_to?(:fetch) ? config.fetch(COMPACTION_CONFIG_KEY, {}) : {}
75
+ cfg = Rubik::Storage::Layout.config_get(config, COMPACTION_CONFIG_KEY, {})
74
76
  cfg.is_a?(Hash) ? cfg : {}
75
77
  end
76
78
 
77
79
  # ── implementation details (not interface) ────────────────────────
78
80
 
79
81
  def auto_recover?(config)
80
- config.respond_to?(:fetch) ? config.fetch(AUTO_RECOVER_KEY, true) : true
82
+ Rubik::Storage::Layout.config_get(config, AUTO_RECOVER_KEY, true)
81
83
  end
82
84
 
83
85
  def overflow_error?(err)
@@ -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
  # Provider-scoped configuration resolution for the orchestrator loop
@@ -50,7 +52,7 @@ module Rubik
50
52
  def llm_config(key, default)
51
53
  prov_key = registry_key
52
54
  if prov_key.is_a?(String) && !prov_key.empty? && @config.respond_to?(:fetch)
53
- val = @config.fetch("providers.#{prov_key}.#{key}", nil)
55
+ val = Rubik::Storage::Layout.config_get(@config, "providers.#{prov_key}.#{key}", nil)
54
56
  return val unless val.nil?
55
57
  end
56
58
 
@@ -60,7 +62,7 @@ module Rubik
60
62
  # KeyError instead of falling through.
61
63
  return default unless @config.respond_to?(:fetch)
62
64
 
63
- @config.fetch("llm.#{key}", default)
65
+ Rubik::Storage::Layout.config_get(@config, "llm.#{key}", default)
64
66
  rescue StandardError
65
67
  default
66
68
  end
@@ -0,0 +1,96 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../prompt"
4
+ require_relative "shell_deps"
5
+
6
+ module Rubik
7
+ module Orchestrator
8
+ # Loop-side resume window (issue #475, the Loop mirror of GoalSession's
9
+ # resume drive from #459). One collaborator owns the three concerns the
10
+ # resume path used to scatter across the run loop:
11
+ #
12
+ # 1. ctx.extend lifecycle — the §6 discipline: an in-process resume
13
+ # disposes the (already run()-disposed) old per-run sub-context
14
+ # BEFORE extending a fresh one, so repeated suspend/resume cycles do
15
+ # not leak dead children; the ensure-side close disposes exactly once.
16
+ # 2. Cross-process history prefix construction — the Σ-only window
17
+ # [system prompt] → [task] → [Σ row], shaped so the first resumed
18
+ # step's ledger refresh repositions (not duplicates) the Σ row.
19
+ # 3. goal_resumed marker stamping — downtime formatting and the
20
+ # 300-character reason discipline, testable without running a turn.
21
+ #
22
+ # System-prompt rendering and state fingerprinting stay on Loop (shared
23
+ # with run()'s prompt view, candidate 2 Phase 2); their VALUES are passed
24
+ # in, so this collaborator renders nothing itself.
25
+ class ResumeWindow
26
+ def initialize(deps)
27
+ @deps = ShellDeps.wrap(deps)
28
+ end
29
+
30
+ # ── ctx.extend lifecycle (§6) ─────────────────────────────────────
31
+ # In-process resume: the suspended run's sub-context is dead already
32
+ # (run()'s ensure disposed it) — dispose again defensively, then
33
+ # extend a fresh child for the resumed window.
34
+ def reopen_context!
35
+ @deps.reopen_run_context!
36
+ end
37
+
38
+ # Cross-process resume: a fresh Loop has no prior sub-context — just
39
+ # extend. Disposing first would be a no-op on nil, but the distinct
40
+ # entry point keeps the two resume paths' invariants explicit.
41
+ def open_context!
42
+ @deps.open_run_context!
43
+ end
44
+
45
+ # ensure-side dispose of the window's sub-context.
46
+ def close_context!
47
+ @deps.dispose_run_context!
48
+ end
49
+
50
+ # ── cross-process history prefix ──────────────────────────────────
51
+ # Builds [system-prompt row] → [task row] → [Σ row] on the loop's
52
+ # history. The system prompt CONTENT is supplied by the caller (Loop
53
+ # renders via its shared prompt view); this method owns the ordering
54
+ # and the Σ-row placement contract.
55
+ def build_cross_process_prefix!(goal_text:, ledger:, system_prompt:)
56
+ history << { role: "system", content: system_prompt }
57
+ history << { role: "user", content: Rubik::Prompt::ContextBuilder.format_user_task(goal_text) }
58
+ history << { role: "user", content: ledger.to_xml }
59
+ end
60
+
61
+ # ── goal_resumed marker ───────────────────────────────────────────
62
+ # Signature row (last link of the cross-process window): role "user"
63
+ # (EmergencyCompactor hard tier does not touch it), single-tag quoting
64
+ # discipline (ledger_row?/drift_row? mold). downtime is human-readable,
65
+ # "unknown" when unknowable. reason obeys the same 300-character
66
+ # discipline as the Σ stamp — 5xx bodies must not bloat history.
67
+ def stamp_resume_marker!(reason:, suspended_at:, attempt:)
68
+ esc = Rubik::Platform.method(:xml_escape)
69
+ history << { role: "user", content: "<goal_resumed downtime=\"#{esc.call(format_downtime(suspended_at))}\" " \
70
+ "reason=\"#{esc.call(reason.to_s.slice(0, 300))}\" attempt=\"#{attempt.to_i}\" " \
71
+ "steps_done=\"#{@deps.step_count}\" />" }
72
+ end
73
+
74
+ private
75
+
76
+ def history
77
+ @deps.history
78
+ end
79
+
80
+ # seconds → "45s" / "4m 12s" / "1h 03m"; honest "unknown" when the
81
+ # suspend time is unavailable (corrupt cross-process meta). Negative
82
+ # drift (clock skew) clamps to 0.
83
+ def format_downtime(suspended_at)
84
+ return "unknown" unless suspended_at.respond_to?(:to_i) && suspended_at.to_i.positive?
85
+
86
+ secs = [(Time.now - suspended_at).to_i, 0].max
87
+ mm, ss = secs.divmod(60)
88
+ hh, mm = mm.divmod(60)
89
+ return "#{hh}h #{mm.to_s.rjust(2, '0')}m" if hh.positive?
90
+ return "#{mm}m #{ss.to_s.rjust(2, '0')}s" if mm.positive?
91
+
92
+ "#{ss}s"
93
+ end
94
+ end
95
+ end
96
+ end
@@ -51,6 +51,22 @@ module Rubik
51
51
  @loop.history = new_history
52
52
  end
53
53
 
54
+ # ResumeWindow lifecycle commands (issue #475): Loop owns the
55
+ # @loop_context ivar; named commands instead of ivar reach-through,
56
+ # per the writes-policy note in the class comment.
57
+ def reopen_run_context!
58
+ dispose_run_context!
59
+ open_run_context!
60
+ end
61
+
62
+ def open_run_context!
63
+ @loop.loop_context = @loop.runtime_manager&.context&.extend
64
+ end
65
+
66
+ def dispose_run_context!
67
+ @loop.loop_context&.dispose
68
+ end
69
+
54
70
  def reset_invalid_tools!
55
71
  @loop.invalid_tool_count = 0
56
72
  end
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "../log"
3
4
  require_relative "finish_message_selector"
4
5
  require_relative "auto_apply"
5
6
  require_relative "tool_call_id"
@@ -217,7 +218,7 @@ module Rubik
217
218
  sink.call(type: :user_output, content: raw_output.to_s, label: raw_output.display_stub,
218
219
  step: @deps.step_count, max_steps: @deps.max_steps)
219
220
  else
220
- warn("[show_file] no :user_output sink wired — display content dropped: #{raw_output.display_stub}")
221
+ Rubik::Log.warn(:orchestrator, "[show_file] no :user_output sink wired — display content dropped: #{raw_output.display_stub}")
221
222
  end
222
223
 
223
224
  Rubik::Tools::Result.new(
@@ -2,6 +2,7 @@
2
2
 
3
3
  require_relative "../llm/chunk_assembler"
4
4
  require_relative "provider_recovery"
5
+ require_relative "../storage/layout"
5
6
 
6
7
  module Rubik
7
8
  module Orchestrator
@@ -88,7 +89,7 @@ module Rubik
88
89
  capture_reasoning = if @deps.respond_to?(:safe_config)
89
90
  @deps.safe_config("llm.capture_reasoning", true) != false
90
91
  elsif @deps.respond_to?(:config) && @deps.config.respond_to?(:fetch)
91
- @deps.config.fetch("llm.capture_reasoning", true) != false
92
+ Rubik::Storage::Layout.config_get(@deps.config, "llm.capture_reasoning", true) != false
92
93
  else
93
94
  true
94
95
  end
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "../../errors"
3
4
  require_relative "budget"
4
5
  require_relative "notices"
5
6
  require_relative "conversation_id"
@@ -19,7 +20,9 @@ module Rubik
19
20
  # this spec — nil for explicitly detached work. A cancelled owner makes
20
21
  # the claim loops drop the spec before it ever starts.
21
22
  class DeferredSpec
22
- class StateError < StandardError; end
23
+ # Unified taxonomy (issue #448): subclasses Rubik::StateError so a
24
+ # caller can rescue any guarded-transition tripwire with one class.
25
+ class StateError < Rubik::StateError; end
23
26
 
24
27
  # The spec machine's every legal from->to edge (Lifecycle family
25
28
  # doctrine: one guarded transition per state machine, fail-loud on