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
@@ -16,12 +16,19 @@ module Rubik
16
16
  # #stderr_tail for diagnostics.
17
17
  STDERR_TAIL_LINES = 20
18
18
 
19
- attr_reader :command, :args, :env, :root_dir, :running, :wait_thr
19
+ # Credential-shaped variable names stripped from the inherited host
20
+ # environment when a server opts out with `inherit_env: false`. Only
21
+ # the suffix shape is policy — the prefix is the provider's choice
22
+ # (GITHUB_TOKEN, ANTHROPIC_API_KEY, ...), so we match it broadly.
23
+ CREDENTIAL_ENV_PATTERN = /_(API_KEY|TOKEN|SECRET|PASSWORD)\z/i
20
24
 
21
- def initialize(command, args: [], env: {}, root_dir: Dir.pwd, guard: nil)
25
+ attr_reader :command, :args, :env, :inherit_env, :root_dir, :running, :wait_thr
26
+
27
+ def initialize(command, args: [], env: {}, inherit_env: true, root_dir: Dir.pwd, guard: nil)
22
28
  @command = command
23
29
  @args = Array(args).map(&:to_s)
24
30
  @env = env || {}
31
+ @inherit_env = self.class.coerce_inherit_env(inherit_env)
25
32
  @root_dir = File.expand_path(root_dir)
26
33
  @guard = guard || Rubik::Security::Guard.new
27
34
  @running = false
@@ -82,14 +89,12 @@ module Rubik
82
89
  resolved_bin = Rubik::Platform.which(bin)
83
90
  cmd_parts[0] = resolved_bin if resolved_bin
84
91
 
85
- string_env = @env.transform_keys(&:to_s).transform_values(&:to_s)
86
-
92
+ # Match the LSP client's spawn hygiene: the host's bundler/Ruby
93
+ # runtime variables are unset for the child, so an MCP server never
94
+ # inherits a foreign BUNDLE_GEMFILE/RUBYOPT. Explicitly configured
95
+ # env: entries merge on top and win.
87
96
  begin
88
- @stdin, @stdout, @stderr, @wait_thr = if string_env.empty?
89
- Open3.popen3(*cmd_parts, chdir: @root_dir)
90
- else
91
- Open3.popen3(string_env, *cmd_parts, chdir: @root_dir)
92
- end
97
+ @stdin, @stdout, @stderr, @wait_thr = Open3.popen3(spawn_env, *cmd_parts, chdir: @root_dir)
93
98
  rescue SystemCallError => e
94
99
  raise ConnectionError, "Failed to spawn MCP process '#{bin}': #{e.message}"
95
100
  end
@@ -251,8 +256,45 @@ module Rubik
251
256
  @wait_thr&.pid
252
257
  end
253
258
 
259
+ class << self
260
+ # Config coercion for `inherit_env:`: only an explicit false
261
+ # (boolean or the string/nil-safe "false") opts out; every other
262
+ # value — including nil and unknown types — keeps the inheriting
263
+ # default so hand-written config cannot accidentally widen the
264
+ # credential hole or break the spawn.
265
+ def coerce_inherit_env(value)
266
+ ![false, "false"].include?(value)
267
+ end
268
+ end
269
+
254
270
  private
255
271
 
272
+ # The environment the child runs in: the host's bundler/Ruby runtime
273
+ # variables are unset (Platform.sanitized_spawn_env — the same scrub
274
+ # list the LSP client applies), then explicitly configured env:
275
+ # entries merge on top and win.
276
+ #
277
+ # Credential policy: by default the child inherits the host env (minus
278
+ # the scrub list) because many MCP servers legitimately need operator
279
+ # credentials (GITHUB_TOKEN etc.). With `inherit_env: false` the child
280
+ # still inherits the host env, but credential-shaped variables
281
+ # (CREDENTIAL_ENV_PATTERN) are additionally unset — spawn override
282
+ # semantics need an explicit nil to remove an inherited variable —
283
+ # leaving the sanitized base plus ONLY the server's explicit env:
284
+ # entries for anything credential-shaped. Explicit env: entries always
285
+ # win in both modes.
286
+ def spawn_env
287
+ base = Rubik::Platform.sanitized_spawn_env
288
+ unless @inherit_env
289
+ ENV.each_key do |key|
290
+ base[key] = nil if key.match?(CREDENTIAL_ENV_PATTERN)
291
+ end
292
+ end
293
+ base.merge(
294
+ @env.transform_keys(&:to_s).transform_values(&:to_s)
295
+ )
296
+ end
297
+
256
298
  def write_message(msg_hash)
257
299
  json = JSON.dump(msg_hash)
258
300
  @mutex.synchronize do
@@ -58,6 +58,8 @@ module Rubik
58
58
  # overrides config resolution entirely — the StepExecutor injection
59
59
  # seam (its tests pass explicit modes positionally).
60
60
  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
+
61
63
  return false if trigger == :pre_execution && !tool.nil? && !test_class_tool?(tool)
62
64
 
63
65
  resolved = mode || (subagent && subagent_flag_on?(config) ? "always" : self.mode(config))
@@ -39,12 +39,20 @@ module Rubik
39
39
  end
40
40
 
41
41
  def evaluate_context_compaction!
42
+ project_goal_ledger_observations! if @deps.respond_to?(:goal_mode?) && @deps.goal_mode?
43
+
42
44
  return unless @deps.context_limit
43
45
 
44
46
  context_cfg = ProviderRecovery.compaction_config(@deps.config)
47
+ reserved = if @deps.respond_to?(:tool_registry) && @deps.tool_registry&.schemas
48
+ Rubik::Prompt::TokenEstimator.estimate_tool_schemas(@deps.tool_registry.schemas)
49
+ else
50
+ 0
51
+ end
45
52
  needs = Rubik::Prompt::ContextCompactor.needs_compaction?(
46
53
  @deps.history, context_limit: @deps.context_limit,
47
- max_output_tokens: @deps.max_output_tokens, config: context_cfg
54
+ max_output_tokens: @deps.max_output_tokens, config: context_cfg,
55
+ reserved_tokens: reserved
48
56
  )
49
57
  return unless needs
50
58
 
@@ -55,12 +63,20 @@ module Rubik
55
63
  @deps.replace_history!(Rubik::Prompt::ContextCompactor.compact_history(
56
64
  @deps.history, context_limit: @deps.context_limit,
57
65
  max_output_tokens: @deps.max_output_tokens, config: context_cfg,
58
- absorb: GoalLedger::ObservationProjection.directive_for(deps: @deps)
66
+ absorb: GoalLedger::ObservationProjection.directive_for(deps: @deps),
67
+ reserved_tokens: reserved
59
68
  ))
60
69
  manager = @deps.runtime_manager if @deps.respond_to?(:runtime_manager)
61
70
  Rubik::Storage::Vakanuvis::Orientation.inject_after_compaction!(@deps.history, manager, config: @deps.config)
62
71
  end
63
72
 
73
+ def project_goal_ledger_observations!
74
+ directive = GoalLedger::ObservationProjection.directive_for(deps: @deps)
75
+ directive&.apply!(@deps.history)
76
+ rescue StandardError => e
77
+ Rubik::Log.warn(:orchestrator, "goal ledger observation projection failed (#{e.class}: #{e.message}); step continues")
78
+ end
79
+
64
80
  def track_token_usage!(res)
65
81
  return unless res.respond_to?(:usage) && res.usage
66
82
 
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rubik
4
+ module Orchestrator
5
+ module GoalLedger
6
+ # Σ ailesinin derin kopya/donma disiplininin TEK evi (aynı iki yordamın
7
+ # ledger/validator/patch'teki beş el kopyası yerine bir sayfa): Hash
8
+ # anahtarları da kopyalanır/donar; yaprak skalarlar paylaşılır (zaten
9
+ # immutable). Ledger include eder, Validator ve Patch extend eder —
10
+ # yöntemler private kalır, yalnız implicit self ile erişilir.
11
+ #
12
+ # Rubik::Config::DeepOps ile aynı adı taşır ama semantiği bilinçli
13
+ # olarak farklıdır: burada yaprak String DUP EDİLMEZ (config kopyası
14
+ # savunmacıdır; Σ dünyasında String'ler zaten JSON round-trip'i ile
15
+ # taze akar — paylaşım güvenlidir ve donma sözleşmesini bozmaz).
16
+ module DeepOps
17
+ private
18
+
19
+ def deep_dup(value)
20
+ case value
21
+ when Hash then value.to_a.to_h { |key, val| [key.dup, deep_dup(val)] }
22
+ when Array then value.map { |val| deep_dup(val) }
23
+ else value
24
+ end
25
+ end
26
+
27
+ def deep_freeze(value)
28
+ case value
29
+ when Hash then value.each do |key, val|
30
+ deep_freeze(key)
31
+ deep_freeze(val)
32
+ end.freeze
33
+ when Array then value.each { |val| deep_freeze(val) }.freeze
34
+ when String then value.freeze
35
+ else value
36
+ end
37
+ end
38
+ end
39
+ end
40
+ end
41
+ end
@@ -63,7 +63,8 @@ module Rubik
63
63
 
64
64
  esc = Rubik::Platform.method(:xml_escape)
65
65
  body = entries.last(Drift::MAX_NOTE_ENTRIES).map { |line| esc.call(line.to_s.slice(0, Drift::MAX_NOTE_CHARS)) }
66
- %(<ledger_drift rev="#{snap['rev']}" entries="#{body.size}">\n #{body.join("\n ")}\n</ledger_drift>)
66
+ tag = Prompt::ContextCompactor::LEDGER_DRIFT_TAG
67
+ %(<#{tag} rev="#{snap['rev']}" entries="#{body.size}">\n #{body.join("\n ")}\n</#{tag}>)
67
68
  end
68
69
  end
69
70
  end
@@ -3,9 +3,9 @@
3
3
  require "time"
4
4
  require "json"
5
5
  require_relative "../../prompt/context_compactor"
6
- require_relative "../../prompt/conversation_rows"
7
6
  require_relative "../../storage/layout"
8
7
  require_relative "../../uris"
8
+ require_relative "deep_ops"
9
9
  require_relative "suspend_lifecycle"
10
10
  require_relative "xml_render"
11
11
 
@@ -36,6 +36,7 @@ module Rubik
36
36
  # log, degrade) doğal erişir. Σ XML render yüzeyi XmlRender'da.
37
37
  include SuspendLifecycle
38
38
  include XmlRender
39
+ include DeepOps
39
40
 
40
41
  # A planı üretim şemasını SAHİPLENİR: goal skeleton örnek örneği
41
42
  # üretim yüzeyi olur (frozen; verify alanları optional+allow_null —
@@ -93,10 +94,35 @@ module Rubik
93
94
  ledger
94
95
  end
95
96
 
96
- # Çapraz-süreç resume fabrikası — gövde SuspendLifecycle'ta
97
- # (satır cap'i disiplini; bozuk/askı-olmayan damga → dürüst nil).
97
+ # Çapraz-süreç resume fabrikası: askı damgası taşıyan Σ satırından
98
+ # defteri yeniden kurar (gövde JSON'u → @doc, links → @last_links,
99
+ # damga meta'sı → suspend_meta). YAZMA YOKTUR — load saf kurulumdur;
100
+ # ilk kabul yeni satır açar. Dürüst red: store / storage_id yok,
101
+ # satır yok, status "suspended" değil ya da gövde bozuksa / Σ
102
+ # şeması eksikse nil — resume handler'ı tek cümlelik ret basar.
103
+ # Şema red'i SAHİLENDİĞİNDE olmalı: eksik koleksiyonlu bir gövde
104
+ # geçse resume render'da NoMethodError ile ölür, oysa unsuspend!
105
+ # damgayı çoktan tüketmiş olurdu. Konum: Ledger üzerinde — kurulum
106
+ # fabrikası host'un kendi işidir; mixin yalnız askı durumunu taşır.
98
107
  def load(store:, storage_id:, config: nil, dmesg: nil, event_bus: nil)
99
- SuspendLifecycle.load(store: store, storage_id: storage_id, config: config, dmesg: dmesg, event_bus: event_bus)
108
+ return nil unless store && storage_id
109
+
110
+ row = store.get(type: "goal", id: storage_id.to_s)
111
+ return nil unless row.is_a?(Hash) && row["status"] == "suspended"
112
+
113
+ doc = JSON.parse(row["body"].to_s)
114
+ return nil unless doc.is_a?(Hash) && doc["rev"].is_a?(Integer) &&
115
+ doc["objective"] && SuspendLifecycle::SIGMA_COLLECTIONS.all? { |key| doc[key].is_a?(Array) }
116
+
117
+ ledger = new(goal_text: doc["objective"].to_s,
118
+ max_retries: max_patch_retries(config),
119
+ store: store, dmesg: dmesg, event_bus: event_bus)
120
+ ledger.restore_from_row!(row: row, doc: doc)
121
+ ledger
122
+ rescue StandardError => e
123
+ Rubik::Log.warn(:goal_ledger, "goal ledger load from suspend stamp failed " \
124
+ "(#{e.class}: #{e.message}); cross-process resume refused")
125
+ nil
100
126
  end
101
127
 
102
128
  def config_get(config, key, default = nil)
@@ -143,7 +169,9 @@ module Rubik
143
169
  return if history.nil? || !history.respond_to?(:reject!)
144
170
 
145
171
  @monitor.synchronize do
146
- history.reject! { |msg| ledger_row?(msg) || drift_row?(msg) }
172
+ # Σ satırı tanıması gramer tek evinden (ContextCompactor):
173
+ # render ve tanıma aynı sabitleri tüketir.
174
+ history.reject! { |msg| Prompt::ContextCompactor.ledger_message?(msg) || Prompt::ContextCompactor.drift_message?(msg) }
147
175
  anchor = history.rindex { |msg| Prompt::ContextCompactor.goal_message?(msg) }
148
176
  if anchor
149
177
  history.insert(anchor + 1, { role: "user", content: render_xml })
@@ -163,10 +191,8 @@ module Rubik
163
191
 
164
192
  @finalized = true
165
193
  if @store && @storage_id
166
- links = @last_links.merge("finish_status" => status.to_s)
167
- row = @store.put(type: "goal", id: @storage_id, title: row_title, body: canonical_json,
168
- tags: ["goal-ledger", "final"], links: links, status: status.to_s)
169
- @storage_id = row["id"]
194
+ stamp_row!(links: @last_links.merge("finish_status" => status.to_s),
195
+ tags: ["goal-ledger", "final"], status: status.to_s)
170
196
  else
171
197
  degrade_storage_once
172
198
  end
@@ -231,19 +257,20 @@ module Rubik
231
257
  { rev: @doc["rev"], objective: @doc["objective"], storage_id: @storage_id,
232
258
  updated_at: @updated_at, finalized: @finalized,
233
259
  suspended: @suspend_meta.is_a?(Hash) && !@finalized,
234
- suspend_meta: @suspend_meta ? deep_dup(@suspend_meta) : nil,
235
- tasks: @doc["tasks"].size,
236
- findings: @doc["findings"].size, decisions: @doc["decisions"].size,
237
- open_questions: @doc["open_questions"].size, environment_notes: @doc["environment_notes"].size }
260
+ suspend_meta: @suspend_meta ? deep_dup(@suspend_meta) : nil }.merge(
261
+ PRODUCTION_SCHEMA.sections.keys.to_h { |name| [name.to_sym, @doc[name].size] }
262
+ )
238
263
  end
239
264
  end
240
265
 
241
266
  private
242
267
 
243
268
  def seed_doc(goal_text)
244
- { "rev" => 0, "objective" => Rubik::Platform.safe_utf8(goal_text.to_s.slice(0, 400)),
245
- "tasks" => [], "findings" => [], "decisions" => [],
246
- "open_questions" => [], "environment_notes" => [] }
269
+ doc = { "rev" => 0, "objective" => Rubik::Platform.safe_utf8(goal_text.to_s.slice(0, 400)) }
270
+ # Σ koleksiyonlarının doğum yeri şemadır (SuspendLifecycle::
271
+ # SIGMA_COLLECTIONS ve snapshot boyutları aynı kaynaktan türetilir).
272
+ PRODUCTION_SCHEMA.sections.each_key { |name| doc[name] = [] }
273
+ doc
247
274
  end
248
275
 
249
276
  def apply!(new_doc)
@@ -285,6 +312,19 @@ module Rubik
285
312
  @store.put(type: "goal", title: title, body: body, tags: tags, links: links, ref: ref)
286
313
  end
287
314
 
315
+ # Satır-adresli damganın tek sahibi (finalize!/suspend!/unsuspend!):
316
+ # id korunur, version++ — put + kimlik takası. Gerisi ÇAĞRI
317
+ # TARAFINDA kalır: idempotence guard'ları, links/tags/status
318
+ # merge'leri, degrade epilogları ve bellek-içi durum sıralaması
319
+ # (@finalized damgadan ÖNCE, @suspend_meta askıda ÖNCE/temizlik
320
+ # başarıdan SONRA) bilinçli olarak bu sıraya bağımlıdır.
321
+ def stamp_row!(links:, tags:, status:)
322
+ row = @store.put(type: "goal", id: @storage_id, title: row_title, body: canonical_json,
323
+ tags: tags, links: links, status: status)
324
+ @storage_id = row["id"]
325
+ row
326
+ end
327
+
288
328
  def canonical_json
289
329
  Rubik::Platform.safe_json_generate(@doc)
290
330
  end
@@ -297,40 +337,6 @@ module Rubik
297
337
  @storage_id ? Rubik::Uris.storage_entity(project: @store.project, type: "goal", id: @storage_id) : nil
298
338
  end
299
339
 
300
- def ledger_row?(msg)
301
- return false unless Prompt::ConversationRows.row?(msg)
302
-
303
- content = Prompt::ConversationRows.content_of(msg).to_s
304
- Prompt::ConversationRows.role_of(msg) == "user" && content.start_with?("<goal_ledger ") && content.include?("</goal_ledger>")
305
- end
306
-
307
- def drift_row?(msg)
308
- return false unless Prompt::ConversationRows.row?(msg)
309
-
310
- content = Prompt::ConversationRows.content_of(msg).to_s
311
- Prompt::ConversationRows.role_of(msg) == "user" && content.start_with?("<ledger_drift ") && content.include?("</ledger_drift>")
312
- end
313
-
314
- def deep_dup(value)
315
- case value
316
- when Hash then value.to_a.to_h { |key, val| [key.dup, deep_dup(val)] }
317
- when Array then value.map { |val| deep_dup(val) }
318
- else value
319
- end
320
- end
321
-
322
- def deep_freeze(value)
323
- case value
324
- when Hash then value.each do |key, val|
325
- deep_freeze(key)
326
- deep_freeze(val)
327
- end.freeze
328
- when Array then value.each { |val| deep_freeze(val) }.freeze
329
- when String then value.dup.freeze
330
- else value
331
- end
332
- end
333
-
334
340
  def log(event, message)
335
341
  unless @dmesg.respond_to?(:log)
336
342
  # Dürüst degradasyon (review 2026-10-10): dmesg yokken telemetri
@@ -85,6 +85,7 @@ module Rubik
85
85
 
86
86
  unit.each do |row|
87
87
  count += 1 if tombstone!(row, rev_now)
88
+ prune_banked_assistant!(row)
88
89
  end
89
90
  end
90
91
  return { count: 0, rev: rev_now, reclaimed_tokens: 0 } if count.zero?
@@ -147,6 +148,31 @@ module Rubik
147
148
  true
148
149
  end
149
150
 
151
+ def prune_banked_assistant!(row)
152
+ return false unless Prompt::ConversationRows.row?(row)
153
+ return false unless Prompt::ConversationRows.role_of(row) == "assistant"
154
+
155
+ tcs = row[:tool_calls] || row["tool_calls"]
156
+ return false unless tcs.is_a?(Array) && !tcs.empty?
157
+
158
+ key = Prompt::ConversationRows.content_key_of(row)
159
+ content = row[key].to_s
160
+ return false if content.include?("<user_task>") || content.include?("<goal_ledger>")
161
+
162
+ modified = false
163
+ if row.key?(:thought) || row.key?("thought")
164
+ row.delete(:thought)
165
+ row.delete("thought")
166
+ modified = true
167
+ end
168
+
169
+ if row.key?(key) && !content.empty?
170
+ row[key] = nil
171
+ modified = true
172
+ end
173
+ modified
174
+ end
175
+
150
176
  def tool_name_of(row)
151
177
  (row[:tool_name] || row["tool_name"]).to_s
152
178
  end
@@ -2,6 +2,8 @@
2
2
 
3
3
  require "json"
4
4
 
5
+ require_relative "deep_ops"
6
+
5
7
  module Rubik
6
8
  module Orchestrator
7
9
  module GoalLedger
@@ -15,16 +17,19 @@ module Rubik
15
17
  # (storage round-trip'inde drift olmaz); yalnızca op'un kendi kontrol
16
18
  # alanları (:op, :path, :tokens, :index) semboldür.
17
19
  class Patch
20
+ # Derin donma disiplini tek sahibi DeepOps'tan gelir; private kalır
21
+ # ve sınıf yordamları içinde implicit self ile erişilir.
22
+ extend DeepOps
23
+
18
24
  OP_VERBS = ["add", "replace", "remove"].freeze
19
25
  OP_KEYS = ["op", "path", "value"].freeze
20
26
  HEADER_KEYS = ["rev", "ops"].freeze
21
27
 
22
- attr_reader :rev, :ops, :raw_bytesize
28
+ attr_reader :rev, :ops
23
29
 
24
- def initialize(rev, ops, raw_bytesize)
30
+ def initialize(rev, ops)
25
31
  @rev = rev
26
32
  @ops = ops
27
- @raw_bytesize = raw_bytesize
28
33
  freeze
29
34
  end
30
35
 
@@ -86,7 +91,7 @@ module Rubik
86
91
  end
87
92
  return [:rejected, reasons] unless reasons.empty?
88
93
 
89
- [:ok, new(rev, ops.freeze, body.bytesize)]
94
+ [:ok, new(rev, ops.freeze)]
90
95
  end
91
96
 
92
97
  # ---- sınıf-içi (private semantik; module_function köprüsü şart değil)
@@ -265,21 +270,9 @@ module Rubik
265
270
  nil
266
271
  end
267
272
 
268
- def self.deep_freeze(value)
269
- case value
270
- when Hash then value.each do |k, v|
271
- deep_freeze(k)
272
- deep_freeze(v)
273
- end.freeze
274
- when Array then value.each { |v| deep_freeze(v) }.freeze
275
- when String then value.dup.freeze
276
- else value # nil / true / false / Integer / Float zaten immutable
277
- end
278
- end
279
-
280
273
  private_class_method :header_reasons, :normalize_op, :op_shape_reason, :verb_inspect,
281
274
  :validate_op_keys, :validate_op_verb_and_path, :validate_op_value_and_hyphen,
282
- :tokenize, :hyphen_violation, :deep_freeze
275
+ :tokenize, :hyphen_violation
283
276
  end
284
277
  end
285
278
  end
@@ -2,6 +2,8 @@
2
2
 
3
3
  require "json"
4
4
 
5
+ require_relative "schema"
6
+
5
7
  module Rubik
6
8
  module Orchestrator
7
9
  module GoalLedger
@@ -19,8 +21,10 @@ module Rubik
19
21
  # degrade sözleşmesi: tek dürüst warn, bellek-içi resume çalışır,
20
22
  # çapraz-süreç resume dürüstçe reddedilir — asla çökmez.
21
23
  module SuspendLifecycle
22
- # Σ çalışma gövdesinin zorunlu koleksiyonları (Ledger.seed_doc moldu).
23
- SIGMA_COLLECTIONS = ["tasks", "findings", "decisions", "open_questions", "environment_notes"].freeze
24
+ # Σ çalışma gövdesinin zorunlu koleksiyonları — şemadan TÜRETİLİR
25
+ # (tek doğum yeri Schema.goal_skeleton; Ledger.seed_doc/snapshot da
26
+ # aynı kaynaktan dolar. Yeni koleksiyon = tek şema düzenmesi).
27
+ SIGMA_COLLECTIONS = Schema.goal_skeleton.sections.keys.freeze
24
28
 
25
29
  # Askı damgası meta'sı (load yolunda satırdan, suspend! yolunda
26
30
  # parametreden): yukarıdaki şema; yoksa nil.
@@ -32,10 +36,8 @@ module Rubik
32
36
 
33
37
  @suspend_meta = deep_dup(meta.to_h.transform_keys(&:to_s))
34
38
  if @store && @storage_id
35
- links = @last_links.merge("suspended" => Rubik::Platform.safe_json_generate(@suspend_meta))
36
- row = @store.put(type: "goal", id: @storage_id, title: row_title, body: canonical_json,
37
- tags: ["goal-ledger"], links: links, status: "suspended")
38
- @storage_id = row["id"]
39
+ stamp_row!(links: @last_links.merge("suspended" => Rubik::Platform.safe_json_generate(@suspend_meta)),
40
+ tags: ["goal-ledger"], status: "suspended")
39
41
  else
40
42
  degrade_storage_once
41
43
  end
@@ -56,9 +58,7 @@ module Rubik
56
58
  return nil if @finalized
57
59
  return nil unless @store && @storage_id
58
60
 
59
- row = @store.put(type: "goal", id: @storage_id, title: row_title, body: canonical_json,
60
- tags: ["goal-ledger"], links: @last_links, status: "active")
61
- @storage_id = row["id"]
61
+ stamp_row!(links: @last_links, tags: ["goal-ledger"], status: "active")
62
62
  @suspend_meta = nil
63
63
  log(:unsuspended, "goal ledger resume at rev #{@doc['rev']}")
64
64
  final_result
@@ -87,38 +87,6 @@ module Rubik
87
87
  self
88
88
  end
89
89
 
90
- class << self
91
- # Çapraz-süreç resume fabrikası: askı damgası taşıyan Σ satırından
92
- # defteri yeniden kurar (gövde JSON'u → @doc, links → @last_links,
93
- # damga meta'sı → suspend_meta). YAZMA YOKTUR — load saf
94
- # kurulumdur; ilk kabul yeni satır açar. Dürüst red: store /
95
- # storage_id yok, satır yok, status "suspended" değil ya da gövde
96
- # bozuksa / Σ şeması eksikse nil — resume handler'ı tek cümlelik
97
- # ret basar. Şema red'i SAHİLENDİĞİNDE olmalı: eksik koleksiyonlu
98
- # bir gövde geçse resume render'da NoMethodError ile ölür, oysa
99
- # unsuspend! damgayı çoktan tüketmiş olurdu.
100
- def load(store:, storage_id:, config: nil, dmesg: nil, event_bus: nil)
101
- return nil unless store && storage_id
102
-
103
- row = store.get(type: "goal", id: storage_id.to_s)
104
- return nil unless row.is_a?(Hash) && row["status"] == "suspended"
105
-
106
- doc = JSON.parse(row["body"].to_s)
107
- return nil unless doc.is_a?(Hash) && doc["rev"].is_a?(Integer) &&
108
- doc["objective"] && SIGMA_COLLECTIONS.all? { |key| doc[key].is_a?(Array) }
109
-
110
- ledger = Ledger.new(goal_text: doc["objective"].to_s,
111
- max_retries: Ledger.max_patch_retries(config),
112
- store: store, dmesg: dmesg, event_bus: event_bus)
113
- ledger.restore_from_row!(row: row, doc: doc)
114
- ledger
115
- rescue StandardError => e
116
- Rubik::Log.warn(:goal_ledger, "goal ledger load from suspend stamp failed " \
117
- "(#{e.class}: #{e.message}); cross-process resume refused")
118
- nil
119
- end
120
- end
121
-
122
90
  private
123
91
 
124
92
  # Satır links'indeki askı damgası meta'sını çözer (bozuk JSON →
@@ -1,5 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "deep_ops"
4
+
3
5
  module Rubik
4
6
  module Orchestrator
5
7
  module GoalLedger
@@ -14,6 +16,10 @@ module Rubik
14
16
  # cap'lidir; validator'u dökümanı sınırsız büyütecek şekilde çağırmak
15
17
  # sözleşme dışıdır).
16
18
  module Validator
19
+ # Derin kopya/donma disiplini tek sahibi DeepOps'tan gelir; private
20
+ # kalır ve validate içinde implicit self ile erişilir.
21
+ extend DeepOps
22
+
17
23
  module_function
18
24
 
19
25
  # patch_or_text: String (önce parse edilir) | GoalLedger::Patch
@@ -335,26 +341,6 @@ module Rubik
335
341
  def rejection(kind, op_index, path, message, hint)
336
342
  GoalLedger.reason(kind, op_index: op_index, path: path, message: message, hint: hint)
337
343
  end
338
-
339
- def deep_dup(value)
340
- case value
341
- when Hash then value.to_a.to_h { |key, val| [key.dup, deep_dup(val)] }
342
- when Array then value.map { |val| deep_dup(val) }
343
- else value
344
- end
345
- end
346
-
347
- def deep_freeze(value)
348
- case value
349
- when Hash then value.each do |key, val|
350
- deep_freeze(key)
351
- deep_freeze(val)
352
- end.freeze
353
- when Array then value.each { |val| deep_freeze(val) }.freeze
354
- when String then value.dup.freeze
355
- else value
356
- end
357
- end
358
344
  end
359
345
  end
360
346
  end
@@ -17,17 +17,10 @@ module Rubik
17
17
  module Verifier
18
18
  module_function
19
19
 
20
- # Adım sınırı girişi (loop.rb execute_steps hook'u): knob FIRST —
21
- # kapalıysa hiç dokunma. goal_mode? guard'ı çağıran taraftadır.
22
- def at_step_boundary!(loop_inst)
23
- ledger = Rubik::Coeffects.get(loop_inst.runtime_manager&.context, Rubik::Coeffects::GOAL_LEDGER)
24
- return nil unless ledger
25
-
26
- verify!(ledger, trigger: :step, root_dir: loop_inst.buffer_manager&.root_dir || Dir.pwd,
27
- config: loop_inst.config)
28
- end
29
-
30
20
  # -> nil (knob off / boş) | {rev:, flipped:, unknowns:, note:}
21
+ # Giriş çözümü çağıranındır (loop.rb verify_goal_ledger!): Verifier
22
+ # yalnız değerlerle konuşur (ledger, root_dir, config) — Loop'un iç
23
+ # yüzünü tanımaz. goal_mode? guard'ı da çağıran taraftadır.
31
24
  def verify!(ledger, trigger:, root_dir:, config: nil)
32
25
  return nil unless Ledger.verify_enabled?(config)
33
26
 
@@ -111,10 +104,6 @@ module Rubik
111
104
  [:failed, "file_contains #{spec[:path]}: needle absent"]
112
105
  end
113
106
 
114
- def stale?(item)
115
- item["status"] == "stale"
116
- end
117
-
118
107
  def entry(collection, idx, item, state, reason)
119
108
  { collection: collection, index: idx, id: item_id(item), state: state, reason: reason,
120
109
  from: item["status"], at: Time.now.utc.iso8601 }