rubik 0.8.1 → 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.
Files changed (148) hide show
  1. checksums.yaml +4 -4
  2. data/ATTRIBUTION.md +2 -2
  3. data/CHANGELOG.md +207 -43
  4. data/README.md +5 -1
  5. data/bin/rubik +15 -10
  6. data/lib/rubik/adapter/base.rb +19 -0
  7. data/lib/rubik/adapter/generic.rb +0 -14
  8. data/lib/rubik/adapter/node.rb +2 -0
  9. data/lib/rubik/ast/treesitter/zig_walker.rb +15 -2
  10. data/lib/rubik/cli/workspace_trust.rb +17 -0
  11. data/lib/rubik/concurrency/worker.rb +143 -0
  12. data/lib/rubik/concurrency.rb +1 -0
  13. data/lib/rubik/config/deep_ops.rb +17 -0
  14. data/lib/rubik/config/defaults.rb +23 -1
  15. data/lib/rubik/config/schema.rb +0 -1
  16. data/lib/rubik/config/store.rb +14 -0
  17. data/lib/rubik/config.rb +7 -3
  18. data/lib/rubik/context/repo_context_reader.rb +27 -8
  19. data/lib/rubik/events.rb +18 -0
  20. data/lib/rubik/kernel/dispatcher.rb +4 -4
  21. data/lib/rubik/kernel/unit.rb +4 -3
  22. data/lib/rubik/log.rb +2 -1
  23. data/lib/rubik/lsp/client.rb +83 -180
  24. data/lib/rubik/lsp/document_store.rb +209 -0
  25. data/lib/rubik/mcp/client.rb +4 -3
  26. data/lib/rubik/mcp/manager.rb +6 -2
  27. data/lib/rubik/mcp/transport/stdio.rb +51 -9
  28. data/lib/rubik/orchestrator/auto_apply.rb +2 -0
  29. data/lib/rubik/orchestrator/budget_manager.rb +18 -2
  30. data/lib/rubik/orchestrator/goal_ledger/deep_ops.rb +41 -0
  31. data/lib/rubik/orchestrator/goal_ledger/drift.rb +2 -1
  32. data/lib/rubik/orchestrator/goal_ledger/ledger.rb +56 -50
  33. data/lib/rubik/orchestrator/goal_ledger/observation_projection.rb +26 -0
  34. data/lib/rubik/orchestrator/goal_ledger/patch.rb +10 -17
  35. data/lib/rubik/orchestrator/goal_ledger/suspend_lifecycle.rb +9 -41
  36. data/lib/rubik/orchestrator/goal_ledger/validator.rb +6 -20
  37. data/lib/rubik/orchestrator/goal_ledger/verifier.rb +3 -14
  38. data/lib/rubik/orchestrator/goal_ledger/xml_render.rb +21 -14
  39. data/lib/rubik/orchestrator/goal_session.rb +505 -0
  40. data/lib/rubik/orchestrator/goal_state.rb +15 -15
  41. data/lib/rubik/orchestrator/loop.rb +62 -63
  42. data/lib/rubik/orchestrator/lsp_feedback.rb +7 -1
  43. data/lib/rubik/orchestrator/subagent/admission_policy.rb +161 -0
  44. data/lib/rubik/orchestrator/subagent/builtin_types.rb +3 -2
  45. data/lib/rubik/orchestrator/subagent/instance.rb +4 -0
  46. data/lib/rubik/orchestrator/subagent/journal.rb +2 -1
  47. data/lib/rubik/orchestrator/subagent/notices.rb +5 -4
  48. data/lib/rubik/orchestrator/subagent/profile_contract.rb +4 -10
  49. data/lib/rubik/orchestrator/subagent/questioner.rb +21 -6
  50. data/lib/rubik/orchestrator/subagent/run_cycle.rb +22 -1
  51. data/lib/rubik/orchestrator/subagent/scoped_registry.rb +34 -2
  52. data/lib/rubik/orchestrator/subagent/step_runner.rb +1 -1
  53. data/lib/rubik/orchestrator/subagent/teardown.rb +4 -0
  54. data/lib/rubik/orchestrator/subagent/transcript_formatter.rb +2 -1
  55. data/lib/rubik/orchestrator/subagent/type_registry.rb +19 -1
  56. data/lib/rubik/orchestrator/turn_executor/subagent_channel.rb +6 -1
  57. data/lib/rubik/orchestrator/turn_executor/user_channel.rb +6 -1
  58. data/lib/rubik/orchestrator/turn_executor.rb +2 -1
  59. data/lib/rubik/orchestrator.rb +1 -0
  60. data/lib/rubik/platform/path.rb +0 -1
  61. data/lib/rubik/platform.rb +15 -0
  62. data/lib/rubik/plugin/storage.rb +20 -29
  63. data/lib/rubik/prompt/context_builder.rb +24 -18
  64. data/lib/rubik/prompt/context_compactor.rb +31 -8
  65. data/lib/rubik/prompt/conversation_rows.rb +33 -0
  66. data/lib/rubik/prompt/doctrine.rb +4 -2
  67. data/lib/rubik/prompt/emergency_compactor.rb +5 -4
  68. data/lib/rubik/repl/commands/agent_context.rb +1 -1
  69. data/lib/rubik/repl/commands/agent_execution.rb +15 -467
  70. data/lib/rubik/repl/commands/buffer.rb +5 -1
  71. data/lib/rubik/repl/commands/lsp.rb +1 -1
  72. data/lib/rubik/repl/commands/mcp.rb +5 -0
  73. data/lib/rubik/repl/commands/subagents.rb +4 -4
  74. data/lib/rubik/repl/commands/workspace.rb +22 -2
  75. data/lib/rubik/repl/config_wiring.rb +24 -7
  76. data/lib/rubik/repl/input_execution.rb +1 -1
  77. data/lib/rubik/repl/input_loop.rb +1 -1
  78. data/lib/rubik/repl/lifecycle.rb +31 -2
  79. data/lib/rubik/repl/pruner/harness.rb +52 -67
  80. data/lib/rubik/repl/pruner/rules.rb +3 -1
  81. data/lib/rubik/repl/service_catalog.rb +1 -1
  82. data/lib/rubik/repl/synthesized_command_context.rb +3 -0
  83. data/lib/rubik/repl/turn_recorder.rb +5 -4
  84. data/lib/rubik/repl.rb +1 -0
  85. data/lib/rubik/runtime/context.rb +5 -0
  86. data/lib/rubik/runtime/discovery.rb +55 -0
  87. data/lib/rubik/runtime/manifest_store.rb +116 -0
  88. data/lib/rubik/runtime/overlay_storage.rb +300 -218
  89. data/lib/rubik/runtime/repair_probe.rb +20 -2
  90. data/lib/rubik/runtime/sealed_coeffects.rb +58 -0
  91. data/lib/rubik/runtime/synthesized_command_context.rb +80 -0
  92. data/lib/rubik/runtime/synthesized_tool_context.rb +123 -0
  93. data/lib/rubik/runtime/task_manager.rb +7 -2
  94. data/lib/rubik/runtime.rb +3 -0
  95. data/lib/rubik/security/allowlist.rb +167 -0
  96. data/lib/rubik/security/audit_log.rb +72 -0
  97. data/lib/rubik/security/classifier/classifier.rb +24 -8
  98. data/lib/rubik/security/classifier/commands/biome.yaml +49 -0
  99. data/lib/rubik/security/classifier/commands/bun.yaml +91 -0
  100. data/lib/rubik/security/classifier/commands/bundle.yaml +107 -0
  101. data/lib/rubik/security/classifier/commands/clang-format.yaml +21 -0
  102. data/lib/rubik/security/classifier/commands/clang.yaml +37 -0
  103. data/lib/rubik/security/classifier/commands/cmake.yaml +37 -0
  104. data/lib/rubik/security/classifier/commands/ctest.yaml +30 -0
  105. data/lib/rubik/security/classifier/commands/gcc.yaml +36 -0
  106. data/lib/rubik/security/classifier/commands/gem.yaml +104 -0
  107. data/lib/rubik/security/classifier/commands/gofmt.yaml +15 -0
  108. data/lib/rubik/security/classifier/commands/pnpm.yaml +8 -8
  109. data/lib/rubik/security/classifier/commands/python.yaml +18 -1
  110. data/lib/rubik/security/classifier/commands/python3.yaml +18 -1
  111. data/lib/rubik/security/classifier/commands/rake.yaml +60 -0
  112. data/lib/rubik/security/classifier/commands/rspec.yaml +42 -0
  113. data/lib/rubik/security/classifier/commands/rubocop.yaml +38 -0
  114. data/lib/rubik/security/classifier/commands/ruby.yaml +25 -0
  115. data/lib/rubik/security/classifier/commands/rustc.yaml +34 -0
  116. data/lib/rubik/security/classifier/commands/zig.yaml +77 -0
  117. data/lib/rubik/security/classifier/database.rb +12 -1
  118. data/lib/rubik/security/classifier/matcher.rb +17 -2
  119. data/lib/rubik/security/classifier/models.rb +3 -2
  120. data/lib/rubik/security/classifier.rb +5 -0
  121. data/lib/rubik/security/command_gate.rb +567 -0
  122. data/lib/rubik/security/guard.rb +96 -989
  123. data/lib/rubik/security/path_policy.rb +117 -0
  124. data/lib/rubik/security/synthesis_gate.rb +300 -0
  125. data/lib/rubik/security.rb +5 -0
  126. data/lib/rubik/storage/ranking.rb +113 -0
  127. data/lib/rubik/storage/store.rb +2 -92
  128. data/lib/rubik/storage/transcript_indexer.rb +2 -3
  129. data/lib/rubik/storage/vakanuvis/harness.rb +49 -89
  130. data/lib/rubik/tools/base.rb +24 -7
  131. data/lib/rubik/tools/builtins/files.rb +2 -0
  132. data/lib/rubik/tools/builtins/goal_ledger.rb +9 -9
  133. data/lib/rubik/tools/builtins/grep.rb +2 -3
  134. data/lib/rubik/tools/builtins/lifecycle.rb +91 -88
  135. data/lib/rubik/tools/builtins/synthesis.rb +124 -64
  136. data/lib/rubik/tools/builtins/unsynthesize.rb +38 -0
  137. data/lib/rubik/tools/catalog.rb +3 -0
  138. data/lib/rubik/tools/declaration.rb +6 -2
  139. data/lib/rubik/tools/lifecycle_rollbacks.rb +87 -0
  140. data/lib/rubik/tools/native_search.rb +2 -1
  141. data/lib/rubik/tools/preflight_runner.rb +107 -14
  142. data/lib/rubik/tools/registry.rb +2 -0
  143. data/lib/rubik/tools/truncator.rb +25 -0
  144. data/lib/rubik/tools/uri_resolver.rb +3 -1
  145. data/lib/rubik/uris.rb +5 -1
  146. data/lib/rubik/version.rb +1 -1
  147. data/lib/rubik.rb +1 -0
  148. metadata +35 -1
@@ -12,10 +12,15 @@ module Rubik
12
12
  @monitor.synchronize { render_xml }
13
13
  end
14
14
 
15
+ def to_json(*_args)
16
+ @monitor.synchronize { Rubik::Platform.safe_json_generate(@doc) }
17
+ end
18
+
15
19
  # §4.1 render: GoalState#to_xml mold'u — tüm metin xml_escape'ten
16
20
  # geçer; boş koleksiyonların etiketi HİÇ basılmaz ("yokluk, boşluk
17
21
  # değil" kuralı); optional attribute'lar (storage_id, verify) yalnız
18
- # set iken basılır.
22
+ # set iken basılır; koleksiyon öğeleri RFC 6902 JSON-pointer adresi
23
+ # için açık `index` taşır.
19
24
  def render_xml
20
25
  esc = Rubik::Platform.method(:xml_escape)
21
26
  attrs = %(rev="#{@doc['rev']}")
@@ -23,36 +28,38 @@ module Rubik
23
28
  attrs += %( updated_at="#{@updated_at.utc.iso8601}") if @updated_at
24
29
  body = []
25
30
  body << %( <objective>#{esc.call(@doc['objective'].to_s)}</objective>)
26
- tasks = @doc["tasks"].map do |task|
31
+ tasks = @doc["tasks"].each_with_index.map do |task, idx|
27
32
  text = task["title"].to_s
28
33
  text += " — notes: #{task['notes']}" if task["notes"]
29
- attrs_t = %(id="#{esc.call(task['id'].to_s)}" status="#{esc.call(task['status'].to_s)}")
30
- attrs_t += %( verify="#{esc.call(task['verify'].to_s)}") if task["verify"]
34
+ attrs_t = %(id="#{esc.call(task['id'].to_s)}" status="#{esc.call(task['status'].to_s)}" index="#{idx}")
35
+ verify_val = task["verify"].is_a?(Hash) ? Rubik::Platform.safe_json_generate(task["verify"]) : task["verify"].to_s
36
+ attrs_t += %( verify="#{esc.call(verify_val)}") if task["verify"]
31
37
  task["title"] || task["notes"] ? %( <task #{attrs_t}>#{esc.call(text)}</task>) : %( <task #{attrs_t} />)
32
38
  end
33
39
  body << "<tasks>\n#{tasks.join("\n")}\n </tasks>" unless tasks.empty?
34
- findings = @doc["findings"].map do |f|
35
- %( <finding id="#{esc.call(f['id'].to_s)}" source_step="#{f['source_step']}">#{esc.call(f['text'].to_s)}</finding>)
40
+ 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>)
36
42
  end
37
43
  body << "<findings>\n#{findings.join("\n")}\n </findings>" unless findings.empty?
38
- decisions = @doc["decisions"].map do |dec|
39
- attrs_d = %(id="#{esc.call(dec['id'].to_s)}")
44
+ decisions = @doc["decisions"].each_with_index.map do |dec, idx|
45
+ attrs_d = %(id="#{esc.call(dec['id'].to_s)}" index="#{idx}")
40
46
  attrs_d += %( rationale="#{esc.call(dec['rationale'].to_s)}") if dec["rationale"]
41
47
  %( <decision #{attrs_d}>#{esc.call(dec['text'].to_s)}</decision>)
42
48
  end
43
49
  body << "<decisions>\n#{decisions.join("\n")}\n </decisions>" unless decisions.empty?
44
- questions = @doc["open_questions"].map { |q| %( <question>#{esc.call(q.to_s)}</question>) }
50
+ questions = @doc["open_questions"].each_with_index.map { |q, idx| %( <question index="#{idx}">#{esc.call(q.to_s)}</question>) }
45
51
  body << "<open_questions>\n#{questions.join("\n")}\n </open_questions>" unless questions.empty?
46
- notes = @doc["environment_notes"].map do |note|
47
- attrs_n = %(id="#{esc.call(note['id'].to_s)}")
48
- attrs_n += %( verify="#{esc.call(note['verify'].to_s)}") if note["verify"]
52
+ notes = @doc["environment_notes"].each_with_index.map do |note, idx|
53
+ attrs_n = %(id="#{esc.call(note['id'].to_s)}" index="#{idx}")
54
+ verify_val = note["verify"].is_a?(Hash) ? Rubik::Platform.safe_json_generate(note["verify"]) : note["verify"].to_s
55
+ attrs_n += %( verify="#{esc.call(verify_val)}") if note["verify"]
49
56
  %( <note #{attrs_n}>#{esc.call(note['text'].to_s)}</note>)
50
57
  end
51
58
  body << "<environment_notes>\n#{notes.join("\n")}\n </environment_notes>" unless notes.empty?
52
59
  <<~XML.strip
53
- <goal_ledger #{attrs}>
60
+ <#{Prompt::ContextCompactor::GOAL_LEDGER_TAG} #{attrs}>
54
61
  #{body.join("\n")}
55
- </goal_ledger>
62
+ </#{Prompt::ContextCompactor::GOAL_LEDGER_TAG}>
56
63
  XML
57
64
  end
58
65
  end
@@ -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
@@ -2,6 +2,7 @@
2
2
 
3
3
  require "monitor"
4
4
  require "time"
5
+ require_relative "../events"
5
6
  require_relative "../platform"
6
7
 
7
8
  module Rubik
@@ -12,12 +13,13 @@ module Rubik
12
13
  # — okuma (read_file) her an güvenli olmalıdır.
13
14
  class GoalState
14
15
  # Bitiş olayının bus adı (Vakanüvis kronikçisinin goal kancası — K3;
15
- # REPL bu olaya abone değildir, notice/wake üretilmez).
16
- FINISH_EVENT = :goal_finished
16
+ # REPL bu olaya abone değildir, notice/wake üretilmez). İsim tek
17
+ # yaprakta: Rubik::Events (bağımlılıksız söz dağarcığı).
18
+ FINISH_EVENT = Rubik::Events::GOAL_FINISHED
17
19
  # Askı olayının bus adı (issue #106): transient transport hatası
18
20
  # goal'u terminal değil SUSPENDED'a götürür — kronikçi askıyı da
19
21
  # görsün; REPL yine abone değildir.
20
- SUSPEND_EVENT = :goal_suspended
22
+ SUSPEND_EVENT = Rubik::Events::GOAL_SUSPENDED
21
23
 
22
24
  def initialize(event_bus: nil)
23
25
  @monitor = Monitor.new
@@ -87,15 +89,6 @@ module Rubik
87
89
  self
88
90
  end
89
91
 
90
- def record_tokens!(usage)
91
- @monitor.synchronize do
92
- u = usage.to_h
93
- @tokens[:input] += u[:input].to_i
94
- @tokens[:output] += u[:output].to_i
95
- end
96
- self
97
- end
98
-
99
92
  def complete!(output_summary = nil, tokens: nil)
100
93
  @monitor.synchronize do
101
94
  return self unless @status == :running
@@ -138,9 +131,16 @@ module Rubik
138
131
  return self unless @status == :running
139
132
 
140
133
  @last_error = Rubik::Platform.safe_utf8(reason.to_s).slice(0, 300)
141
- t = tokens.to_h
142
- @tokens[:input] += t[:input].to_i
143
- @tokens[:output] += t[:output].to_i
134
+ if tokens
135
+ # Mutlak atama (restore_counters! moldu): Loop'un kümülatif
136
+ # token sayacı SSOT'tur. += askı→resume→askı döngüsünde ilk
137
+ # askının kullanımını iki kez sayardı — mutlak atama idempotent
138
+ # kalır ve Σ damgasıyla hep aynı değeri taşır. tokens: nil
139
+ # mevcut değerleri korur (sayaç korunumu sözleşmesi).
140
+ t = tokens.to_h
141
+ @tokens = { input: (t[:input] || t["input"]).to_i,
142
+ output: (t[:output] || t["output"]).to_i }
143
+ end
144
144
  @status = :suspended
145
145
  end
146
146
  notify_suspend