rubik 0.10.0 → 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 (55) hide show
  1. checksums.yaml +4 -4
  2. data/ATTRIBUTION.md +1 -1
  3. data/CHANGELOG.md +61 -1
  4. data/lib/rubik/ast/extractor.rb +2 -1
  5. data/lib/rubik/ast/treesitter_extractor.rb +2 -1
  6. data/lib/rubik/benchmark/vakanuvis_adoption.rb +2 -1
  7. data/lib/rubik/config/secret_policy.rb +6 -5
  8. data/lib/rubik/config/store.rb +2 -1
  9. data/lib/rubik/config.rb +2 -2
  10. data/lib/rubik/context/ignore_rules.rb +193 -0
  11. data/lib/rubik/context/scanner.rb +46 -161
  12. data/lib/rubik/llm/client.rb +6 -200
  13. data/lib/rubik/llm/connection_pool.rb +104 -0
  14. data/lib/rubik/llm/registry.rb +3 -2
  15. data/lib/rubik/llm/sse_parser.rb +110 -0
  16. data/lib/rubik/lsp/circuit_breaker.rb +98 -0
  17. data/lib/rubik/lsp/client_provisioner.rb +49 -0
  18. data/lib/rubik/lsp/manager.rb +55 -88
  19. data/lib/rubik/mcp/manager.rb +25 -13
  20. data/lib/rubik/orchestrator/auto_apply.rb +4 -3
  21. data/lib/rubik/orchestrator/goal_ledger/ledger.rb +12 -1
  22. data/lib/rubik/orchestrator/goal_ledger/schema_vocabulary.rb +38 -0
  23. data/lib/rubik/orchestrator/goal_ledger/xml_render.rb +6 -1
  24. data/lib/rubik/orchestrator/goal_ledger.rb +1 -0
  25. data/lib/rubik/orchestrator/lsp_feedback.rb +1 -1
  26. data/lib/rubik/orchestrator/step_executor.rb +2 -1
  27. data/lib/rubik/orchestrator/subagent/notices.rb +2 -2
  28. data/lib/rubik/orchestrator/subagent/transcript_formatter.rb +2 -1
  29. data/lib/rubik/platform/io_drain.rb +3 -1
  30. data/lib/rubik/plugin/storage.rb +8 -8
  31. data/lib/rubik/repl/config_wiring.rb +5 -3
  32. data/lib/rubik/repl/input_execution.rb +4 -3
  33. data/lib/rubik/repl/lifecycle.rb +1 -1
  34. data/lib/rubik/repl/tee_io.rb +2 -1
  35. data/lib/rubik/runtime/ast_service.rb +2 -1
  36. data/lib/rubik/runtime/overlay_storage.rb +17 -17
  37. data/lib/rubik/runtime/task_manager.rb +1 -1
  38. data/lib/rubik/sandbox/runner.rb +5 -4
  39. data/lib/rubik/security/audit_log.rb +2 -1
  40. data/lib/rubik/security/command_gate.rb +11 -152
  41. data/lib/rubik/security/guard.rb +1 -1
  42. data/lib/rubik/security/secret_store.rb +32 -3
  43. data/lib/rubik/security/segment_report.rb +161 -0
  44. data/lib/rubik/session/recorder.rb +2 -1
  45. data/lib/rubik/skills/manager.rb +2 -1
  46. data/lib/rubik/storage/transcript_indexer.rb +3 -2
  47. data/lib/rubik/storage/vakanuvis.rb +2 -1
  48. data/lib/rubik/tools/builtins/goal_ledger.rb +12 -1
  49. data/lib/rubik/tools/builtins/synthesis.rb +3 -3
  50. data/lib/rubik/tools/preflight_runner.rb +2 -1
  51. data/lib/rubik/tools/uri_resolver.rb +3 -2
  52. data/lib/rubik/ui/capability.rb +1 -0
  53. data/lib/rubik/version.rb +1 -1
  54. data/lib/rubik.rb +3 -3
  55. metadata +8 -1
@@ -0,0 +1,110 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rubik
4
+ module LLM
5
+ # Buffers raw bytes from a stream and emits complete events.
6
+ # Default delimiter is the SSE blank line (\n\n); pass
7
+ # `terminator: "\n"` to parse NDJSON streams (one JSON object per line).
8
+ # One event is a Hash like:
9
+ # { type: "message", data: "json-string" }
10
+ # In SSE mode, multi-line `data:` fields are joined with \n. In NDJSON
11
+ # mode (`terminator: "\n"`), the `type` field is always "message" and
12
+ # the entire line is the `data`. Incomplete events are held in the
13
+ # internal buffer until the next feed.
14
+ class SSEParser
15
+ SSE_EVENT_SEP = /\r\n\r\n|\n\n|\r\n\n|\n\r\n|\r\r/
16
+ SSE_TERMINATOR = "\n\n"
17
+ NDJSON_TERMINATOR = "\n"
18
+
19
+ def initialize(terminator: SSE_TERMINATOR)
20
+ @terminator = terminator
21
+ @sse_mode = @terminator == SSE_TERMINATOR || @terminator == SSE_EVENT_SEP
22
+ @buffer = String.new(encoding: Encoding::UTF_8)
23
+ end
24
+
25
+ # Feed raw bytes; returns an array of complete events parsed from this
26
+ # chunk. Partial events stay in the buffer.
27
+ def feed(chunk_bytes)
28
+ incoming = chunk_bytes.to_s.dup.force_encoding(Encoding::UTF_8)
29
+ incoming = incoming.scrub unless incoming.valid_encoding?
30
+ @buffer << incoming
31
+ drain_complete_events(final: false)
32
+ end
33
+
34
+ # Flush any trailing event (no trailing terminator) and reset.
35
+ def flush
36
+ return [] if @buffer.empty?
37
+
38
+ events = drain_complete_events(final: true)
39
+
40
+ unless @buffer.empty?
41
+ remaining = @buffer.dup
42
+ @buffer = String.new(encoding: Encoding::UTF_8)
43
+ parsed = parse_event(remaining)
44
+ events << parsed if parsed
45
+ end
46
+
47
+ events
48
+ end
49
+
50
+ private
51
+
52
+ # The one drain loop, shared by feed and flush. The SSE and NDJSON
53
+ # branches differ only in how they locate the next terminator. The
54
+ # chunk-boundary \r guard applies only while feeding: if the match
55
+ # ends on \r at the very end of the buffer, wait for the next feed
56
+ # to see if \n follows (e.g. \r\r could become \r\r\n). At flush
57
+ # there is no next feed, so the trailing \r is a real separator.
58
+ def drain_complete_events(final:)
59
+ events = []
60
+ if @sse_mode
61
+ while (m = @buffer.match(SSE_EVENT_SEP))
62
+ break if !final && m.end(0) == @buffer.bytesize && @buffer.end_with?("\r")
63
+
64
+ event_block = @buffer[0...m.begin(0)]
65
+ @buffer = @buffer[m.end(0)..] || String.new(encoding: Encoding::UTF_8)
66
+ parsed = parse_event(event_block)
67
+ events << parsed if parsed
68
+ end
69
+ else
70
+ while (idx = @buffer.index(@terminator))
71
+ event_block = @buffer[0...idx]
72
+ @buffer = @buffer[(idx + @terminator.length)..] || String.new(encoding: Encoding::UTF_8)
73
+ parsed = parse_event(event_block)
74
+ events << parsed if parsed
75
+ end
76
+ end
77
+ events
78
+ end
79
+
80
+ def parse_event(block)
81
+ return nil if block.nil?
82
+ return { type: "message", data: block.to_s.chomp } unless @sse_mode
83
+
84
+ lines = block.to_s.split(/\r\n|\r|\n/)
85
+ return nil if lines.empty?
86
+
87
+ event_type = "message"
88
+ data_lines = []
89
+ has_field = false
90
+
91
+ lines.each do |line|
92
+ next if line.empty?
93
+ next if line.start_with?(":")
94
+
95
+ if (m = line.match(/\Aevent:\s*(.+)\z/))
96
+ event_type = m[1]
97
+ has_field = true
98
+ elsif (m = line.match(/\Adata:\s?(.*)\z/))
99
+ data_lines << m[1]
100
+ has_field = true
101
+ end
102
+ end
103
+
104
+ return nil unless has_field
105
+
106
+ { type: event_type, data: data_lines.join("\n") }
107
+ end
108
+ end
109
+ end
110
+ end
@@ -0,0 +1,98 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "monitor"
4
+
5
+ module Rubik
6
+ module LSP
7
+ # Per-language circuit breaker for LSP server processes (extracted from
8
+ # Manager, issue #497). After `MAX_CONSECUTIVE_CRASHES` consecutive
9
+ # crashes the circuit opens and automatic restarts are refused for
10
+ # `CIRCUIT_COOLDOWN_SECONDS`; sustained healthy operation
11
+ # (`CIRCUIT_STABILITY_SECONDS` without a crash) retires the crash
12
+ # history. Modeled on Orchestrator::ToolCircuitBreaker.
13
+ #
14
+ # Thread-safety: self-contained behind its own Monitor (a leaf object —
15
+ # callers may hold their own locks around these calls without deadlock).
16
+ class CircuitBreaker
17
+ MAX_CONSECUTIVE_CRASHES = 3
18
+ CIRCUIT_COOLDOWN_SECONDS = 300
19
+ CIRCUIT_STABILITY_SECONDS = 60
20
+
21
+ # `clock` overrides the monotonic time source (test seam); the Manager
22
+ # wires it to its own `monotonic_now` so existing clock stubs keep
23
+ # working.
24
+ def initialize(clock: nil)
25
+ @monitor = Monitor.new
26
+ @clock = clock
27
+ @crash_stats = {}
28
+ @healthy_since = {}
29
+ end
30
+
31
+ # Live per-language crash-history hash ({ count:, last_crash_at:,
32
+ # circuit_open: }); exposed for status reporting and test observability.
33
+ attr_reader :crash_stats
34
+
35
+ def open?(lang)
36
+ lang_str = lang.to_s.downcase
37
+ @monitor.synchronize do
38
+ retire_if_stable!(lang_str)
39
+
40
+ stat = @crash_stats[lang_str]
41
+ return false unless stat && stat[:circuit_open]
42
+
43
+ if stat[:last_crash_at] && (monotonic_now - stat[:last_crash_at] > CIRCUIT_COOLDOWN_SECONDS)
44
+ stat[:circuit_open] = false
45
+ stat[:count] = 0
46
+ false
47
+ else
48
+ true
49
+ end
50
+ end
51
+ end
52
+
53
+ def record_crash(lang)
54
+ lang_str = lang.to_s.downcase
55
+ @monitor.synchronize do
56
+ healthy_since = @healthy_since.delete(lang_str)
57
+ @crash_stats.delete(lang_str) if healthy_since && monotonic_now - healthy_since >= CIRCUIT_STABILITY_SECONDS
58
+ stat = (@crash_stats[lang_str] ||= { count: 0, last_crash_at: nil, circuit_open: false })
59
+ stat[:count] += 1
60
+ stat[:last_crash_at] = monotonic_now
61
+ stat[:circuit_open] = true if stat[:count] >= MAX_CONSECUTIVE_CRASHES
62
+ end
63
+ end
64
+
65
+ def note_healthy_start(lang)
66
+ lang_str = lang.to_s.downcase
67
+ @monitor.synchronize { @healthy_since[lang_str] = monotonic_now }
68
+ end
69
+
70
+ def reset!(lang)
71
+ lang_str = lang.to_s.downcase
72
+ @monitor.synchronize do
73
+ @crash_stats.delete(lang_str)
74
+ @healthy_since[lang_str] = monotonic_now
75
+ end
76
+ end
77
+
78
+ # Drop crash history for a language that has run stably for
79
+ # CIRCUIT_STABILITY_SECONDS. `open?` folds this in automatically.
80
+ def retire_if_stable!(lang)
81
+ lang_str = lang.to_s.downcase
82
+ @monitor.synchronize do
83
+ healthy_since = @healthy_since[lang_str]
84
+ return unless healthy_since && monotonic_now - healthy_since >= CIRCUIT_STABILITY_SECONDS
85
+
86
+ @crash_stats.delete(lang_str)
87
+ @healthy_since.delete(lang_str)
88
+ end
89
+ end
90
+
91
+ private
92
+
93
+ def monotonic_now
94
+ @clock ? @clock.call : Process.clock_gettime(Process::CLOCK_MONOTONIC)
95
+ end
96
+ end
97
+ end
98
+ end
@@ -0,0 +1,49 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "client"
4
+ require_relative "server_command"
5
+ require_relative "../storage/layout"
6
+ require_relative "../runtime/discovery"
7
+ require_relative "../runtime/diagnostic_engine"
8
+
9
+ module Rubik
10
+ module LSP
11
+ # Client provisioning policy for LSP servers (extracted from Manager,
12
+ # issue #497): resolve the configured server command, build a Client,
13
+ # fall back to Runtime::Discovery probing when the configured binary is
14
+ # unavailable, and diagnose the failure when nothing usable is found.
15
+ #
16
+ # Plain, lock-free collaborator — the Manager owns all locking and
17
+ # invokes `provision` while holding its monitor.
18
+ class ClientProvisioner
19
+ def initialize(config:, root_dir:)
20
+ @config = config
21
+ @root_dir = root_dir
22
+ end
23
+
24
+ # Resolve a client for `lang`. Returns { client:, diagnosis: } —
25
+ # `client` is always a Client instance (usable or not); `diagnosis` is
26
+ # a Runtime::ExecutionFailure when no server binary could be found,
27
+ # nil when the client is available.
28
+ def provision(lang, existing: nil)
29
+ configured_cmd = Rubik::Storage::Layout.config_get(@config, "lsp.servers.#{lang}", nil) || Client::SERVERS[lang]
30
+ client = existing || Client.new(lang, root_dir: @root_dir, server_cmd: configured_cmd)
31
+
32
+ # Fallback probing if the configured command binary is not available
33
+ unless client.available?
34
+ probed_cmd = Runtime::Discovery.probe_lsp(lang, root_dir: @root_dir, custom_cmd: configured_cmd)
35
+ client = Client.new(lang, root_dir: @root_dir, server_cmd: probed_cmd) if probed_cmd && !probed_cmd.eql?(client.server_cmd)
36
+ end
37
+
38
+ return { client: client, diagnosis: nil } if client.available?
39
+
40
+ failure = Runtime::DiagnosticEngine.diagnose(
41
+ cmd: ServerCommand.display(client.server_cmd),
42
+ exit_code: 127,
43
+ stderr: "Server binary '#{ServerCommand.display(client.server_cmd)}' not found in PATH"
44
+ )
45
+ { client: client, diagnosis: failure }
46
+ end
47
+ end
48
+ end
49
+ end
@@ -2,6 +2,9 @@
2
2
 
3
3
  require "monitor"
4
4
  require_relative "client"
5
+ require_relative "circuit_breaker"
6
+ require_relative "client_provisioner"
7
+ require_relative "server_command"
5
8
  require_relative "../storage/layout"
6
9
  require_relative "../runtime/discovery"
7
10
  require_relative "../runtime/diagnostic_engine"
@@ -9,6 +12,10 @@ require_relative "../runtime/diagnostic_engine"
9
12
  module Rubik
10
13
  module LSP
11
14
  class Manager
15
+ # LSP server ids. Deliberately diverges from
16
+ # Context::Scanner::EXTENSION_MAP (which maps to index language
17
+ # tags); the two tables serve different consumers — keep them
18
+ # separate.
12
19
  EXTENSION_MAP = {
13
20
  ".go" => "go",
14
21
  ".rs" => "rust",
@@ -39,11 +46,13 @@ module Rubik
39
46
  ".bash" => "shellscript"
40
47
  }.freeze
41
48
 
42
- MAX_CONSECUTIVE_CRASHES = 3
43
- CIRCUIT_COOLDOWN_SECONDS = 300
44
- CIRCUIT_STABILITY_SECONDS = 60
49
+ # Circuit-breaker policy lives in CircuitBreaker (issue #497); the
50
+ # constants are re-exposed here for API compatibility.
51
+ MAX_CONSECUTIVE_CRASHES = CircuitBreaker::MAX_CONSECUTIVE_CRASHES
52
+ CIRCUIT_COOLDOWN_SECONDS = CircuitBreaker::CIRCUIT_COOLDOWN_SECONDS
53
+ CIRCUIT_STABILITY_SECONDS = CircuitBreaker::CIRCUIT_STABILITY_SECONDS
45
54
 
46
- attr_reader :config, :root_dir, :clients, :crash_stats
55
+ attr_reader :config, :root_dir, :clients
47
56
  # :nodoc: test observability door — read-only view of the per-language
48
57
  # disposable-registration tracking (issue #450). No production consumer.
49
58
  attr_reader :registered_disposable_langs
@@ -55,14 +64,19 @@ module Rubik
55
64
  @runtime_manager = runtime_manager
56
65
  @context = context || runtime_manager&.context
57
66
  @clients = {}
58
- @crash_stats = {}
59
- @healthy_since = {}
67
+ @breaker = CircuitBreaker.new(clock: -> { monotonic_now })
68
+ @provisioner = ClientProvisioner.new(config: @config, root_dir: @root_dir)
60
69
  @recovery_errors = {}
61
70
  @registered_disposable_langs = {}
62
71
  @client_inverses = {}
63
72
  @monitor = Monitor.new
64
73
  end
65
74
 
75
+ # Per-language crash history (live hash from the CircuitBreaker).
76
+ def crash_stats
77
+ @breaker.crash_stats
78
+ end
79
+
66
80
  def enabled?
67
81
  Rubik::Storage::Layout.config_get(@config, "lsp.enabled", false) == true
68
82
  end
@@ -81,46 +95,18 @@ module Rubik
81
95
  DOCUMENT_LANGUAGE_ID_MAP[ext] || detect_language(file_path) || "plaintext"
82
96
  end
83
97
 
98
+ # Circuit-breaker state machine (extracted to CircuitBreaker, #497);
99
+ # Manager keeps the public delegating API.
84
100
  def circuit_open?(lang)
85
- @monitor.synchronize do
86
- stat = @crash_stats[lang.to_s.downcase]
87
- healthy_since = @healthy_since[lang.to_s.downcase]
88
- if healthy_since && monotonic_now - healthy_since >= CIRCUIT_STABILITY_SECONDS
89
- @crash_stats.delete(lang.to_s.downcase)
90
- @healthy_since.delete(lang.to_s.downcase)
91
- return false
92
- end
93
-
94
- return false unless stat && stat[:circuit_open]
95
-
96
- if stat[:last_crash_at] && (monotonic_now - stat[:last_crash_at] > CIRCUIT_COOLDOWN_SECONDS)
97
- stat[:circuit_open] = false
98
- stat[:count] = 0
99
- false
100
- else
101
- true
102
- end
103
- end
101
+ @breaker.open?(lang)
104
102
  end
105
103
 
106
104
  def record_crash(lang)
107
- @monitor.synchronize do
108
- lang_str = lang.to_s.downcase
109
- healthy_since = @healthy_since.delete(lang_str)
110
- @crash_stats.delete(lang_str) if healthy_since && monotonic_now - healthy_since >= CIRCUIT_STABILITY_SECONDS
111
- stat = (@crash_stats[lang_str] ||= { count: 0, last_crash_at: nil, circuit_open: false })
112
- stat[:count] += 1
113
- stat[:last_crash_at] = monotonic_now
114
- stat[:circuit_open] = true if stat[:count] >= MAX_CONSECUTIVE_CRASHES
115
- end
105
+ @breaker.record_crash(lang)
116
106
  end
117
107
 
118
108
  def reset_circuit!(lang)
119
- @monitor.synchronize do
120
- lang_str = lang.to_s.downcase
121
- @crash_stats.delete(lang_str)
122
- @healthy_since[lang_str] = monotonic_now
123
- end
109
+ @breaker.reset!(lang)
124
110
  end
125
111
 
126
112
  def ensure_healthy!(language_or_client)
@@ -145,21 +131,10 @@ module Rubik
145
131
  def start_client(lang)
146
132
  lang_str = lang.to_s.downcase
147
133
  @monitor.synchronize do
148
- configured_cmd = Rubik::Storage::Layout.config_get(@config, "lsp.servers.#{lang_str}", nil) || Client::SERVERS[lang_str]
149
- client = @clients[lang_str] || Client.new(lang_str, root_dir: @root_dir, server_cmd: configured_cmd)
150
-
151
- # 1. Fallback probing if configured command binary is not available
152
- unless client.available?
153
- probed_cmd = Runtime::Discovery.probe_lsp(lang_str, root_dir: @root_dir, custom_cmd: configured_cmd)
154
- client = Client.new(lang_str, root_dir: @root_dir, server_cmd: probed_cmd) if probed_cmd && probed_cmd != client.server_cmd
155
- end
134
+ outcome = @provisioner.provision(lang_str, existing: @clients[lang_str])
135
+ client = outcome[:client]
156
136
 
157
- unless client.available?
158
- failure = Runtime::DiagnosticEngine.diagnose(
159
- cmd: ServerCommand.display(client.server_cmd),
160
- exit_code: 127,
161
- stderr: "Server binary '#{ServerCommand.display(client.server_cmd)}' not found in PATH"
162
- )
137
+ if (failure = outcome[:diagnosis])
163
138
  return {
164
139
  ok: false,
165
140
  error: "Server binary '#{ServerCommand.display(client.server_cmd)}' not found",
@@ -179,10 +154,7 @@ module Rubik
179
154
  register_client_unlocked(lang_str, client)
180
155
  { ok: true, message: "Started LSP server for '#{lang_str}' (#{ServerCommand.display(client.server_cmd)})" }
181
156
  else
182
- record_crash(lang_str)
183
- stop_client_safely(client)
184
- @clients.delete(lang_str)
185
- unregister_client_unlocked(lang_str)
157
+ restart_failed(lang_str, client, drop_stored: true)
186
158
  failure = Runtime::DiagnosticEngine.diagnose(
187
159
  cmd: ServerCommand.display(client.server_cmd),
188
160
  exit_code: 1,
@@ -392,19 +364,14 @@ module Rubik
392
364
  # Caller MUST hold @monitor. Dead-client removal and replacement startup
393
365
  # happen in one critical section so concurrent requests share one client.
394
366
  def client_for_unlocked(lang, preferred = nil)
395
- circuit_open?(lang) # also retires crash history after sustained healthy operation
367
+ @breaker.open?(lang) # also retires crash history after sustained healthy operation
396
368
  stored = @clients[lang]
397
369
  client = stored || preferred
398
370
  recovering = false
399
371
 
400
372
  if client && client_dead?(client)
401
373
  recovering = true
402
- record_crash(lang)
403
- stop_client_safely(client)
404
- if stored.equal?(client)
405
- @clients.delete(lang)
406
- unregister_client_unlocked(lang)
407
- end
374
+ restart_failed(lang, client, drop_stored: true, unregister: stored.equal?(client))
408
375
  client = nil
409
376
  end
410
377
 
@@ -420,23 +387,14 @@ module Rubik
420
387
  return nil unless client || enabled?
421
388
 
422
389
  if client.nil?
423
- configured_cmd = Rubik::Storage::Layout.config_get(@config, "lsp.servers.#{lang}", nil) || Client::SERVERS[lang]
424
- client = Client.new(lang, root_dir: @root_dir, server_cmd: configured_cmd)
425
- unless client.available?
426
- probed_cmd = Runtime::Discovery.probe_lsp(lang, root_dir: @root_dir, custom_cmd: configured_cmd)
427
- client = Client.new(lang, root_dir: @root_dir, server_cmd: probed_cmd) if probed_cmd
428
- end
390
+ outcome = @provisioner.provision(lang)
391
+ client = outcome[:client]
429
392
 
430
393
  if client.available? && Rubik::Storage::Layout.config_get(@config, "lsp.auto_start", true) && !circuit_open?(lang)
431
394
  if client.start
432
- note_healthy_start(lang)
433
- @recovery_errors.delete(lang)
434
- register_client_unlocked(lang, client)
395
+ start_succeeded(lang, client)
435
396
  else
436
- record_crash(lang)
437
- stop_client_safely(client)
438
- unregister_client_unlocked(lang)
439
- @recovery_errors[lang] = "LSP server restart failed for '#{lang}'" if recovering
397
+ restart_failed(lang, client, reason: recovering ? "LSP server restart failed for '#{lang}'" : nil)
440
398
  end
441
399
  elsif recovering
442
400
  @recovery_errors[lang] = if circuit_open?(lang)
@@ -451,20 +409,33 @@ module Rubik
451
409
  elsif !client.running && Rubik::Storage::Layout.config_get(@config, "lsp.auto_start", true) &&
452
410
  client.available? && !circuit_open?(lang)
453
411
  if client.start
454
- note_healthy_start(lang)
455
- @recovery_errors.delete(lang)
456
- register_client_unlocked(lang, client)
412
+ start_succeeded(lang, client)
457
413
  else
458
- record_crash(lang)
459
- stop_client_safely(client)
460
- unregister_client_unlocked(lang)
461
- @recovery_errors[lang] = "LSP server restart failed for '#{lang}'" if recovering
414
+ restart_failed(lang, client, reason: recovering ? "LSP server restart failed for '#{lang}'" : nil)
462
415
  end
463
416
  end
464
417
 
465
418
  client
466
419
  end
467
420
 
421
+ # Shared failure path for the restart branches: count the crash, tear
422
+ # the client down, drop its registration, and (optionally) record the
423
+ # recovery error shown to later callers. Caller MUST hold @monitor.
424
+ def restart_failed(lang, client, reason: nil, drop_stored: false, unregister: true)
425
+ record_crash(lang)
426
+ stop_client_safely(client)
427
+ @clients.delete(lang) if drop_stored && @clients[lang].equal?(client)
428
+ unregister_client_unlocked(lang) if unregister
429
+ @recovery_errors[lang] = reason if reason
430
+ end
431
+
432
+ # Success path counterpart of restart_failed. Caller MUST hold @monitor.
433
+ def start_succeeded(lang, client)
434
+ @breaker.note_healthy_start(lang)
435
+ @recovery_errors.delete(lang)
436
+ register_client_unlocked(lang, client)
437
+ end
438
+
468
439
  def client_dead?(client)
469
440
  (client.running && client.respond_to?(:alive?) && !client.alive?) ||
470
441
  (client.respond_to?(:crashed?) && client.crashed?)
@@ -507,10 +478,6 @@ module Rubik
507
478
  Process.clock_gettime(Process::CLOCK_MONOTONIC)
508
479
  end
509
480
 
510
- def note_healthy_start(lang)
511
- @healthy_since[lang.to_s.downcase] = monotonic_now
512
- end
513
-
514
481
  def inactive_client_error(file_path, client)
515
482
  lang = client&.language || detect_language(file_path)
516
483
  @monitor.synchronize do
@@ -136,7 +136,7 @@ module Rubik
136
136
  client =
137
137
  if @client_factory
138
138
  @client_factory.call(cmd, args: args, env: env, **inherit_env_kwarg, name: name_str, root_dir: @root_dir,
139
- guard: @guard || (base_ctx ? Rubik::Coeffects.get(base_ctx, Rubik::Coeffects::GUARD) : nil))
139
+ guard: resolve_guard(base_ctx))
140
140
  else
141
141
  Rubik::MCP::Client.new(
142
142
  cmd,
@@ -148,7 +148,7 @@ module Rubik
148
148
  # Manager built before wire_runtime_context still picks up the
149
149
  # session guard once the context provides it (construction-time
150
150
  # snapshots of coeffects go stale — this matches base_ctx above).
151
- guard: @guard || (base_ctx ? Rubik::Coeffects.get(base_ctx, Rubik::Coeffects::GUARD) : nil),
151
+ guard: resolve_guard(base_ctx),
152
152
  call_timeout: call_timeout
153
153
  )
154
154
  end
@@ -169,6 +169,24 @@ module Rubik
169
169
  end
170
170
  end
171
171
 
172
+ # The single boot race gate (D5), checked at apply time under the
173
+ # monitor: a disable/remove/enable during boot wins over the boot's
174
+ # own apply, and a stop_all skips it entirely. Epoch-complete: this
175
+ # boot may only apply into the slot its own phase-0 claim marked,
176
+ # so a user decision that moved the slot or a newer boot's fresh
177
+ # mark wins. Callers hold @monitor.
178
+ def boot_gate_open?(name_str, epoch)
179
+ !@stopped && @statuses[name_str] == :connecting && @boot_marks[name_str].equal?(epoch)
180
+ end
181
+
182
+ # Resolved live at connect time: the composed kwarg wins, but a
183
+ # Manager built before wire_runtime_context still picks up the
184
+ # session guard once the context provides it (construction-time
185
+ # snapshots of coeffects go stale — matches base_ctx).
186
+ def resolve_guard(base_ctx)
187
+ @guard || (base_ctx ? Rubik::Coeffects.get(base_ctx, Rubik::Coeffects::GUARD) : nil)
188
+ end
189
+
172
190
  # Apply phase of enable_server: the post-connect half, extracted
173
191
  # verbatim — context wiring FIRST (so any later failure cleans up via
174
192
  # the child drain), proxy registration, registry flips, and the
@@ -247,7 +265,7 @@ module Rubik
247
265
  end
248
266
 
249
267
  @monitor.synchronize do
250
- if @stopped || @statuses[name_str] != :connecting || !@boot_marks[name_str].equal?(epoch)
268
+ unless boot_gate_open?(name_str, epoch)
251
269
  safely_stop_rolled_back_client(connected[:client], name_str)
252
270
  return @clients[name_str]
253
271
  end
@@ -365,22 +383,16 @@ module Rubik
365
383
  # only receives the decision.
366
384
  def boot_apply_gate(name_str, parsed_defn, boot_epoch, client:, tools:)
367
385
  @monitor.synchronize do
368
- # Single race gate (D5), checked at apply time under the
369
- # monitor: a disable/remove/enable during boot wins over
370
- # the boot's own apply, and a stop_all skips it entirely.
371
- # Epoch-complete gate: this boot may only apply into the
372
- # slot its own phase-0 claim marked, so a user decision
373
- # that moved the slot or a newer boot's fresh mark wins.
374
386
  # In the synchronous path nothing can interleave, so the
375
- # guard is provably inert there.
376
- if @stopped || @statuses[name_str] != :connecting || !@boot_marks[name_str].equal?(boot_epoch)
377
- :skipped
378
- else
387
+ # gate is provably inert there.
388
+ if boot_gate_open?(name_str, boot_epoch)
379
389
  apply_connected_server(name_str, parsed_defn, client: client, tools: tools)
380
390
  # Post-apply revalidation under the boot actor: a no-op
381
391
  # when apply already landed :active.
382
392
  transition_server!(name_str, :active, epoch: boot_epoch)
383
393
  :applied
394
+ else
395
+ :skipped
384
396
  end
385
397
  end
386
398
  end
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "../log"
3
4
  require_relative "subagent/notices"
4
5
  require_relative "../storage/layout"
5
6
 
@@ -109,11 +110,11 @@ module Rubik
109
110
  Subagent::Notices.emit(event_bus, Subagent::Notices::AUTO_APPLY_FAILED_EVENT,
110
111
  { id: id, role: role, state: state.to_s, reason: reason })
111
112
  else
112
- warn("[AutoApply] subagent '#{id}' auto-apply (#{trigger}) failed: #{reason}")
113
+ Rubik::Log.warn(:orchestrator, "[AutoApply] subagent '#{id}' auto-apply (#{trigger}) failed: #{reason}")
113
114
  end
114
115
  rescue StandardError => e
115
- warn("[AutoApply] subagent '#{id}' auto-apply (#{trigger}) failed: #{reason} " \
116
- "(notice emit also failed: #{e.class}: #{e.message})")
116
+ Rubik::Log.warn(:orchestrator, "[AutoApply] subagent '#{id}' auto-apply (#{trigger}) failed: #{reason} " \
117
+ "(notice emit also failed: #{e.class}: #{e.message})")
117
118
  end
118
119
  end
119
120
 
@@ -87,6 +87,13 @@ module Rubik
87
87
  config_get(config, "goal.ledger.max_patch_retries", DEFAULT_MAX_RETRIES).to_i
88
88
  end
89
89
 
90
+ # Model-yüzü sözlük: SchemaVocabulary'ün PRODUCTION_SCHEMA'dan
91
+ # türettiği tek satır (frozen şema → memoize güvenli). Tool
92
+ # description'ı ile tükenme feedback'i bu tek türevi paylaşır.
93
+ def schema_vocabulary
94
+ @schema_vocabulary ||= SchemaVocabulary.render(PRODUCTION_SCHEMA)
95
+ end
96
+
90
97
  def create!(goal_text:, config: nil, store: nil, dmesg: nil, event_bus: nil)
91
98
  ledger = new(goal_text: goal_text.to_s, max_retries: max_patch_retries(config),
92
99
  store: store, dmesg: dmesg, event_bus: event_bus)
@@ -142,8 +149,12 @@ module Rubik
142
149
  # Ret sayacı ardışıktır; başarı sıfırlar; bütçe aşımında :exhausted
143
150
  # döner ve ESKİ Σ korunur (goal loop asla brick olmaz).
144
151
  def update(patch_or_text)
145
- verdict = Validator.validate(patch_or_text, schema: PRODUCTION_SCHEMA, current_doc: @doc)
146
152
  @monitor.synchronize do
153
+ # Validation reads @doc; keep it inside the monitor so a
154
+ # concurrent reader/writer cannot slip between validate and
155
+ # apply! (validation is pure — no IO — so holding the lock is
156
+ # free of deadlock risk).
157
+ verdict = Validator.validate(patch_or_text, schema: PRODUCTION_SCHEMA, current_doc: @doc)
147
158
  if verdict[0] == :ok
148
159
  apply!(verdict[1])
149
160
  elsif @rejections >= @max_retries
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rubik
4
+ module Orchestrator
5
+ module GoalLedger
6
+ # Model-yüzü sözlük türetme yüzeyi. SSOT disiplini: Σ şemasının tek
7
+ # gerçek kaynağı Ledger::PRODUCTION_SCHEMA'dır; enum/required/optional
8
+ # bilgisi buradan TEK noktadan türetilir ve üç statik teaching yüzeyine
9
+ # dağıtılır (tool description — yüklenme anı, Σ XML sayfası — her adım
10
+ # başı reinject, tükenme feedback'i). Elle yazılan enum/alan kopyası
11
+ # YOKTUR: şema değişirse sözlük değişir. Durum-bağımsızdır — rev/drift
12
+ # ile hiçbir ilişkisi olmadığı için bayatlayamaz (drift felsefesi:
13
+ # bayat teşhis bilgi zehridir; sözlük teşhis değil, gramerdir) ve tek
14
+ # sabit satır olduğu için pinli Σ satırını şişirmez.
15
+ module SchemaVocabulary
16
+ module_function
17
+
18
+ # Tek satırlık, deterministik sözlük: item-section'lar için alan
19
+ # mühürleri (* required, ? optional) ve enum dağarcığı, skalar
20
+ # listeler için tip. Hash ekleme sırası korunur → deterministik.
21
+ def render(schema)
22
+ sections = schema.sections.map do |name, section|
23
+ if section.scalar
24
+ "#{name}:string-list"
25
+ else
26
+ fields = section.item.fields.map do |fname, spec|
27
+ "#{fname}#{spec.optional ? '?' : '*'}#{":#{spec.enum.join('|')}" if spec.enum}"
28
+ end
29
+ "#{name}(#{fields.join(',')})"
30
+ end
31
+ end
32
+ "#{sections.join(' ')} — * required, ? optional; append items via /<section>/-, " \
33
+ "one op per item; wholesale section writes are rejected"
34
+ end
35
+ end
36
+ end
37
+ end
38
+ end