rubik 0.13.0 → 0.14.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 (101) hide show
  1. checksums.yaml +4 -4
  2. data/ATTRIBUTION.md +1 -1
  3. data/CHANGELOG.md +34 -1
  4. data/lib/rubik/ast/c_extractor.rb +1 -1
  5. data/lib/rubik/ast/graph.rb +38 -57
  6. data/lib/rubik/ast/graph_extensions.rb +57 -15
  7. data/lib/rubik/ast/ruby_extractor.rb +4 -0
  8. data/lib/rubik/ast/treesitter/c_walker.rb +11 -3
  9. data/lib/rubik/buffer/manager.rb +33 -11
  10. data/lib/rubik/buffer/snapshot.rb +23 -3
  11. data/lib/rubik/cli/connect.rb +3 -5
  12. data/lib/rubik/config/defaults.rb +3 -7
  13. data/lib/rubik/config/env_guard.rb +43 -0
  14. data/lib/rubik/config/schema.rb +7 -1
  15. data/lib/rubik/config/secret_policy.rb +6 -5
  16. data/lib/rubik/config.rb +1 -1
  17. data/lib/rubik/connect/models_dev.rb +9 -0
  18. data/lib/rubik/connect/probes.rb +9 -2
  19. data/lib/rubik/connect/wizard.rb +108 -56
  20. data/lib/rubik/context/repo_context_reader.rb +8 -4
  21. data/lib/rubik/llm/chunk_assembler.rb +12 -1
  22. data/lib/rubik/llm/formatter.rb +14 -0
  23. data/lib/rubik/llm/provider_key.rb +32 -0
  24. data/lib/rubik/llm/registry.rb +18 -2
  25. data/lib/rubik/llm/router.rb +19 -1
  26. data/lib/rubik/llm/session_header.rb +128 -0
  27. data/lib/rubik/llm/sse_parser.rb +57 -10
  28. data/lib/rubik/lsp/client.rb +11 -5
  29. data/lib/rubik/lsp/transport.rb +17 -7
  30. data/lib/rubik/mcp/transport/stdio.rb +42 -4
  31. data/lib/rubik/orchestrator/continuation_manager.rb +14 -5
  32. data/lib/rubik/orchestrator/goal_ledger/ledger.rb +18 -2
  33. data/lib/rubik/orchestrator/goal_ledger/observation_projection.rb +13 -4
  34. data/lib/rubik/orchestrator/goal_ledger/validator.rb +46 -7
  35. data/lib/rubik/orchestrator/goal_ledger/verifier.rb +8 -1
  36. data/lib/rubik/orchestrator/goal_session.rb +4 -4
  37. data/lib/rubik/orchestrator/loop.rb +8 -11
  38. data/lib/rubik/orchestrator/provider_resolver.rb +29 -6
  39. data/lib/rubik/orchestrator/step_executor.rb +17 -2
  40. data/lib/rubik/orchestrator/subagent/instance.rb +24 -1
  41. data/lib/rubik/orchestrator/subagent/notices.rb +1 -1
  42. data/lib/rubik/orchestrator/subagent/reaper.rb +21 -2
  43. data/lib/rubik/orchestrator/subagent/start_gate.rb +1 -1
  44. data/lib/rubik/orchestrator/subagent/step_runner.rb +7 -7
  45. data/lib/rubik/orchestrator/subagent/supervisor.rb +10 -3
  46. data/lib/rubik/orchestrator/turn_executor/user_channel.rb +27 -5
  47. data/lib/rubik/orchestrator/turn_executor.rb +24 -8
  48. data/lib/rubik/platform/filesystem.rb +52 -24
  49. data/lib/rubik/plugin/storage.rb +20 -0
  50. data/lib/rubik/prompt/context_builder.rb +2 -1
  51. data/lib/rubik/repair/loop.rb +22 -2
  52. data/lib/rubik/repl/commands/agent_context.rb +1 -1
  53. data/lib/rubik/repl/commands/agent_execution.rb +20 -15
  54. data/lib/rubik/repl/commands/buffer.rb +15 -0
  55. data/lib/rubik/repl/commands/connect.rb +0 -1
  56. data/lib/rubik/repl/commands/lsp.rb +1 -1
  57. data/lib/rubik/repl/commands/plugins.rb +31 -31
  58. data/lib/rubik/repl/commands/session.rb +5 -5
  59. data/lib/rubik/repl/commands/workspace.rb +4 -4
  60. data/lib/rubik/repl/input_execution.rb +30 -29
  61. data/lib/rubik/repl/input_loop.rb +9 -4
  62. data/lib/rubik/repl/lifecycle.rb +1 -2
  63. data/lib/rubik/repl/notice_router.rb +11 -5
  64. data/lib/rubik/repl/paste_support.rb +1 -1
  65. data/lib/rubik/repl/prompt_grace.rb +3 -3
  66. data/lib/rubik/repl/shell.rb +10 -2
  67. data/lib/rubik/repl/turn_recorder.rb +14 -3
  68. data/lib/rubik/runtime/context.rb +33 -27
  69. data/lib/rubik/runtime/manager.rb +23 -15
  70. data/lib/rubik/sandbox/driver/bubblewrap.rb +58 -8
  71. data/lib/rubik/sandbox/driver/process.rb +32 -1
  72. data/lib/rubik/sandbox/runner.rb +9 -1
  73. data/lib/rubik/security/classifier/classifier.rb +147 -13
  74. data/lib/rubik/security/classifier/commands/docker.yaml +1 -1
  75. data/lib/rubik/security/classifier/commands/git.yaml +27 -1
  76. data/lib/rubik/security/classifier/commands/sed.yaml +3 -3
  77. data/lib/rubik/security/classifier/database.rb +2 -2
  78. data/lib/rubik/security/command_gate.rb +8 -1
  79. data/lib/rubik/security/redactor.rb +62 -19
  80. data/lib/rubik/session/recorder.rb +13 -18
  81. data/lib/rubik/session/replayer.rb +29 -7
  82. data/lib/rubik/storage/store.rb +19 -5
  83. data/lib/rubik/tools/builtins/exec.rb +1 -1
  84. data/lib/rubik/tools/builtins/files.rb +8 -12
  85. data/lib/rubik/tools/builtins/grep.rb +3 -2
  86. data/lib/rubik/tools/builtins/lsp.rb +31 -7
  87. data/lib/rubik/tools/builtins/show_file.rb +1 -1
  88. data/lib/rubik/tools/builtins/synthesis.rb +4 -4
  89. data/lib/rubik/tools/result_normalizer.rb +1 -1
  90. data/lib/rubik/ui/banner.rb +3 -3
  91. data/lib/rubik/ui/dialog.rb +10 -7
  92. data/lib/rubik/ui/diff_viewer.rb +4 -4
  93. data/lib/rubik/ui/frame.rb +13 -3
  94. data/lib/rubik/ui/markdown_stream.rb +8 -2
  95. data/lib/rubik/ui/panel.rb +11 -11
  96. data/lib/rubik/ui/renderer.rb +6 -6
  97. data/lib/rubik/ui/spinner.rb +1 -1
  98. data/lib/rubik/ui/statusline.rb +3 -3
  99. data/lib/rubik/ui/theme.rb +1 -1
  100. data/lib/rubik/version.rb +1 -1
  101. metadata +4 -1
@@ -48,6 +48,13 @@ subcommands:
48
48
  ls-remote:
49
49
  classification: READONLY
50
50
  strict: false
51
+ # Transport/config options that spawn a shell or hijack execution (issue #539).
52
+ options:
53
+ --upload-pack: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
54
+ --receive-pack: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
55
+ --exec: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
56
+ -c: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
57
+ --config: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
51
58
  ls-tree:
52
59
  classification: READONLY
53
60
  strict: false
@@ -307,16 +314,33 @@ subcommands:
307
314
  pull:
308
315
  classification: LOCAL_EFFECTS
309
316
  strict: false
317
+ options:
318
+ --upload-pack: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
319
+ --receive-pack: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
320
+ --exec: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
321
+ -c: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
322
+ --config: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
310
323
  fetch:
311
324
  classification: LOCAL_EFFECTS
312
325
  risk: LOW
313
326
  strict: false
314
327
  options:
315
328
  --prune: {overrides: LOCAL_EFFECTS}
329
+ --upload-pack: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
330
+ --receive-pack: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
331
+ --exec: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
332
+ -c: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
333
+ --config: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
316
334
  clone:
317
335
  classification: LOCAL_EFFECTS
318
336
  risk: LOW
319
337
  strict: false
338
+ options:
339
+ --upload-pack: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
340
+ --receive-pack: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
341
+ --exec: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
342
+ -c: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
343
+ --config: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
320
344
  init:
321
345
  classification: LOCAL_EFFECTS
322
346
  risk: LOW
@@ -436,7 +460,9 @@ subcommands:
436
460
  classification: READONLY
437
461
  strict: false
438
462
  foreach:
439
- classification: READONLY
463
+ # git evaluates the argument as a shell command in every submodule;
464
+ # typing the payload directly would be DANGEROUS (issue #539).
465
+ classification: DANGEROUS
440
466
  strict: false
441
467
  init:
442
468
  classification: LOCAL_EFFECTS
@@ -1,7 +1,7 @@
1
1
  # $schema: ../../../schemas/command.schema.json
2
2
  command: sed
3
3
  description: "Stream editor for filtering and transforming text"
4
- classification: READONLY
4
+ classification: LOCAL_EFFECTS
5
5
  strict: false
6
6
  global_options:
7
7
  --help: {overrides: READONLY}
@@ -10,5 +10,5 @@ options:
10
10
  --in-place: {overrides: DANGEROUS, risk: HIGH, aliases: [-i]}
11
11
  -e: {takes_value: true}
12
12
  --expression: {takes_value: true, aliases: [-e]}
13
- -f: {takes_value: true}
14
- --file: {takes_value: true, aliases: [-f]}
13
+ -f: {overrides: DANGEROUS, risk: HIGH, takes_value: true}
14
+ --file: {overrides: DANGEROUS, risk: HIGH, takes_value: true, aliases: [-f]}
@@ -81,7 +81,7 @@ module Rubik
81
81
  key_s = self.class.yaml_str(key)
82
82
  return true if shell == :powershell && PwshRules.key?(key_s)
83
83
 
84
- @cache.key?(key_s) || @files.key?(key_s) || PwshRules.key?(key_s)
84
+ synchronize { @cache.key?(key_s) || @files.key?(key_s) || PwshRules.key?(key_s) }
85
85
  end
86
86
 
87
87
  def resolve_alias(command_def)
@@ -97,7 +97,7 @@ module Rubik
97
97
  end
98
98
 
99
99
  def keys
100
- (@files.keys + PwshRules.definitions.keys).uniq
100
+ synchronize { (@files.keys + PwshRules.definitions.keys).uniq }
101
101
  end
102
102
 
103
103
  def size
@@ -197,7 +197,14 @@ module Rubik
197
197
  block_ambiguous_parse!(ast, cmd_str)
198
198
  end
199
199
 
200
- return true if [:readonly, :local_effects, :external_effects].include?(ast.classification) && ast.parse_warnings.empty?
200
+ # Classification-based allow verdicts must not skip the un-bypassable
201
+ # fallback regex: every other allow path runs it (directly or via
202
+ # operator_allowlist_pass?). An under-rated database entry must not
203
+ # become a silent full bypass of the final safety layer.
204
+ if [:readonly, :local_effects, :external_effects].include?(ast.classification) && ast.parse_warnings.empty?
205
+ verify_command_fallback_regex!(cmd_str)
206
+ return true
207
+ end
201
208
  rescue BlockedWriteError
202
209
  raise
203
210
  rescue StandardError => e
@@ -17,8 +17,15 @@ module Rubik
17
17
  %r{(https?://[^\s/@:]+:)([^\s/@:]+)@}
18
18
  ].freeze
19
19
 
20
- ASSIGNMENT_KEY_REGEX = /\b(password|passwd|api_key|secret)(\s*[:=]\s*)(['"][^'"]*['"]|[^\s,;'"]+)/i
21
- ASSIGNMENT_TOKEN_REGEX = /\b(token)(\s*[:=]\s*)(['"][^'"]*['"]|[^\s,;'"]+)/i
20
+ # Generic NAME <sep> VALUE assignment. The name is normalized (camelCase
21
+ # boundaries -> snake_case, downcase) and classified by #secret_key? at
22
+ # match time, so `password=...`, `OPENAI_API_KEY=...`, `apiKey=...` and the
23
+ # `--key=...` flag form all share ONE rule. The optional `--` prefix is
24
+ # what makes provider CLI flags land here (issue #542).
25
+ ASSIGNMENT_KEY_REGEX = /(--)?\b([A-Za-z][A-Za-z0-9_-]*)(\s*[:=]\s*)(['"][^'"]*['"]|[^\s,;'"]+)/
26
+ # Positional counterpart of `--key=...`: `!provider set <name> key <value>`
27
+ # has no separator, so it needs its own bounded shape (no prose masking).
28
+ CLI_POSITIONAL_KEY_REGEX = /\b(set\s+\S+\s+(?:key|api[_-]?key|secret|token|password|passwd)\s+)(['"][^'"]*['"]|[^\s,;'"]+)/i
22
29
 
23
30
  # PERF: Pre-compiled constants to avoid re-allocation inside hot loops
24
31
  URL_PATTERN = %r{(https?://[^\s/@:]+:)([^\s/@:]+)@}
@@ -26,13 +33,18 @@ module Rubik
26
33
  STATIC_PATTERNS = PATTERNS.reject { |pattern| pattern == URL_PATTERN }.freeze
27
34
  # Skip static replacement passes for assignment-only and URL-only inputs.
28
35
  STATIC_PATTERNS_COMBINED_REGEX = Regexp.union(STATIC_PATTERNS).freeze
29
- QUICK_CHECK_REGEX = %r{sk-|AKIA|ghp_|github_pat_|AIza|bearer|PRIVATE KEY|://[^\s/@:]+:|password|passwd|api_key|secret|token}i
36
+ # `key` is load-bearing: without it `--key=...` and `apiKey` take the
37
+ # fast path and keep the credential verbatim (issue #542).
38
+ QUICK_CHECK_REGEX = %r{sk-|AKIA|ghp_|github_pat_|AIza|bearer|PRIVATE KEY|://[^\s/@:]+:|password|passwd|api_key|secret|token|\bkey\b}i
30
39
 
31
40
  # Anahtar-maskeleme desenleri (Session::Recorder#mask_payload ile aynı
32
41
  # aile): sır görünümlü anahtarların değerleri desen eşleşmese bile
33
- # maskelenir; sayaç anahtarları (tokens, max_tokens) istisnadır.
34
- SECRET_KEY_REGEX = /(api_key|auth|password|secret|_token\b|^token\b)/i
35
- TOKEN_COUNT_REGEX = /(tokens|token_count|max_tokens)/i
42
+ # maskelenir. Her iki desen de NORMALİZE anahtara uygulanır; sayaç
43
+ # istisnası tam adla eşleşir, yoksa `auth_tokens` gibi bir sır anahtarı
44
+ # `tokens` alt dizgisi yüzünden yanlışlıkla istisna sayılırdı (#542).
45
+ SECRET_KEY_REGEX = /(?:api_key|auth|password|passwd|secret|_token\z|\Atoken\b|\bkey\b)/i
46
+ TOKEN_COUNT_REGEX = /\A(?:tokens|token_count|max_tokens)\z/i
47
+ TOKEN_NAME_REGEX = /(?:\Atoken\b|_token\z)/i
36
48
 
37
49
  def self.redact(text)
38
50
  return text unless text.is_a?(String)
@@ -59,23 +71,56 @@ module Rubik
59
71
  result.gsub!(URL_PATTERN, URL_MASK)
60
72
 
61
73
  result.gsub!(ASSIGNMENT_KEY_REGEX) do
62
- "#{Regexp.last_match(1)}#{Regexp.last_match(2)}#{MASK_STRING}"
63
- end
64
-
65
- result.gsub!(ASSIGNMENT_TOKEN_REGEX) do |match|
66
- prefix = Regexp.last_match(1)
67
- sep = Regexp.last_match(2)
68
- val = Regexp.last_match(3)
69
- if val =~ /\A['"]?\d+['"]?\z/
70
- match
74
+ full = Regexp.last_match(0)
75
+ flag = Regexp.last_match(1)
76
+ name = Regexp.last_match(2)
77
+ sep = Regexp.last_match(3)
78
+ value = Regexp.last_match(4)
79
+ if maskable_assignment?(name, value)
80
+ "#{flag}#{name}#{sep}#{MASK_STRING}"
71
81
  else
72
- "#{prefix}#{sep}#{MASK_STRING}"
82
+ full
73
83
  end
74
84
  end
75
85
 
86
+ result.gsub!(CLI_POSITIONAL_KEY_REGEX) do
87
+ "#{Regexp.last_match(1)}#{MASK_STRING}"
88
+ end
89
+
76
90
  result
77
91
  end
78
92
 
93
+ # camelCase / SCREAMING_SNAKE -> lower snake_case, so one vocabulary
94
+ # recognizes `apiKey`, `APIKey`, `OPENAI_API_KEY` and `api_key` alike.
95
+ # Both patterns are FIXED-LENGTH: the old `([A-Z]+)([A-Z][a-z])` had a
96
+ # repeated class immediately followed by an overlapping class, which
97
+ # backtracks polynomially on a long uppercase run (CodeQL rb/polynomial-
98
+ # redos). Matching a single uppercase before the boundary is equivalent
99
+ # — the preceding uppercase chars are simply copied — and linear.
100
+ def self.normalize_key(key)
101
+ key.to_s
102
+ .gsub(/([A-Z])([A-Z][a-z])/, '\1_\2')
103
+ .gsub(/([a-z\d])([A-Z])/, '\1_\2')
104
+ .downcase
105
+ end
106
+
107
+ # True for a secret-looking key, with counter names excluded by EXACT
108
+ # match (so `auth_tokens` stays a secret while `max_tokens` does not).
109
+ def self.secret_key?(key)
110
+ normalized = normalize_key(key)
111
+ normalized.match?(SECRET_KEY_REGEX) && !normalized.match?(TOKEN_COUNT_REGEX)
112
+ end
113
+
114
+ # Token-valued assignments keep a numeric value (the existing contract:
115
+ # `token: 20` / `max_tokens: 100` are counters, not credentials).
116
+ def self.maskable_assignment?(name, value)
117
+ normalized = normalize_key(name)
118
+ return false unless normalized.match?(SECRET_KEY_REGEX) && !normalized.match?(TOKEN_COUNT_REGEX)
119
+ return false if normalized.match?(TOKEN_NAME_REGEX) && value.to_s.match?(/\A['"]?\d+['"]?\z/)
120
+
121
+ true
122
+ end
123
+
79
124
  # Bir payload ağacında (Hash/Array/String) her metne redact uygular ve
80
125
  # sır görünümlü anahtarların değerlerini komple maskeler — kalıcı
81
126
  # serileştirmeden önce satır başına çağrılır (transcript sağlığı
@@ -88,9 +133,7 @@ module Rubik
88
133
  case payload
89
134
  when Hash
90
135
  payload.each_with_object({}) do |(k, v), h|
91
- key_str = k.to_s
92
- is_secret_key = key_str.match?(SECRET_KEY_REGEX) && !key_str.match?(TOKEN_COUNT_REGEX)
93
- h[k] = is_secret_key ? MASK_STRING : mask_value(v)
136
+ h[k] = secret_key?(k) ? MASK_STRING : mask_value(v)
94
137
  end
95
138
  when Array
96
139
  payload.map { |v| mask_value(v) }
@@ -16,6 +16,14 @@ module Rubik
16
16
 
17
17
  attr_reader :session_file, :events
18
18
 
19
+ # The session identity spelled everywhere else (parent_session_id
20
+ # stamps, session listings, LLM session-header derivation): the file
21
+ # basename without extension. Single-homed so a filename-scheme
22
+ # change cannot silently fork downstream spellings.
23
+ def session_id
24
+ File.basename(@session_file.to_s, ".jsonl")
25
+ end
26
+
19
27
  def initialize(sessions_dir: nil, session_name: nil, root_dir: Dir.pwd, home_dir: ENV.fetch("HOME", nil)) # rubocop:disable Lint/UnusedMethodArgument -- arayüz kwarg'i korunuyor
20
28
  @sessions_dir = sessions_dir || File.join(root_dir, ".rubik", "sessions")
21
29
  begin
@@ -125,25 +133,12 @@ module Rubik
125
133
  event
126
134
  end
127
135
 
136
+ # SSOT: the subagent channel masks with Redactor.mask_value, so the
137
+ # session recorder must delegate to the very same routine — a second
138
+ # copy of the key vocabulary drifts (camelCase, counter exclusions,
139
+ # env-style assignments) the moment one side is hardened (issue #542).
128
140
  def mask_payload(payload)
129
- case payload
130
- when Hash
131
- payload.each_with_object({}) do |(k, v), h|
132
- key_str = k.to_s
133
- is_secret_key = key_str.match?(/(api_key|auth|password|secret|_token\b|^token\b)/i) && !key_str.match?(/(tokens|token_count|max_tokens)/i)
134
- h[k] = if is_secret_key
135
- "***MASKED***"
136
- else
137
- mask_payload(v)
138
- end
139
- end
140
- when Array
141
- payload.map { |v| mask_payload(v) }
142
- when String
143
- mask_text(payload)
144
- else
145
- payload
146
- end
141
+ Rubik::Security::Redactor.mask_value(payload)
147
142
  end
148
143
  end
149
144
  end
@@ -7,6 +7,22 @@ module Rubik
7
7
  class Replayer
8
8
  DESTRUCTIVE_COMMANDS = ["apply", "sh", "rm", "execute"].freeze
9
9
 
10
+ # The recorder's current event vocabulary plus the legacy pair. Only
11
+ # input-shaped events are re-executed; output-shaped ones are still
12
+ # recognized (and reported in replayed_events) so a current-format
13
+ # session is no longer a no-op for `!replay` (issue #562).
14
+ INPUT_EVENT_TYPES = ["input", "command", "prompt", "user_turn", "repl_command"].freeze
15
+ EVENT_TEXT_KEYS = {
16
+ "input" => ["raw", "input", "content"],
17
+ "command" => ["raw", "input", "command"],
18
+ "prompt" => ["raw", "input", "content"],
19
+ "user_turn" => ["content", "text", "raw"],
20
+ "repl_command" => ["command", "raw"],
21
+ "assistant_response" => ["content", "text", "output"],
22
+ "tool_call" => ["tool", "name"],
23
+ "tool_result" => ["tool", "name", "output"]
24
+ }.freeze
25
+
10
26
  attr_reader :shell, :replayed_events, :skipped_events
11
27
 
12
28
  def initialize(shell)
@@ -37,18 +53,24 @@ module Rubik
37
53
  private
38
54
 
39
55
  def process_event(event)
40
- type = event["type"]
41
- payload = event["payload"]
56
+ type = event["type"].to_s
57
+ keys = EVENT_TEXT_KEYS[type]
58
+ return unless keys
42
59
 
43
- return unless ["input", "command"].include?(type)
44
-
45
- cmd_text = payload.is_a?(Hash) ? (payload["raw"] || payload["input"]) : payload.to_s
60
+ payload = event["payload"]
61
+ cmd_text = if payload.is_a?(Hash)
62
+ keys.filter_map { |key| payload[key] }.first
63
+ else
64
+ payload.to_s
65
+ end
66
+ return if cmd_text.nil? || cmd_text.to_s.strip.empty?
46
67
 
47
- if destructive?(cmd_text)
68
+ input_event = INPUT_EVENT_TYPES.include?(type)
69
+ if input_event && destructive?(cmd_text)
48
70
  @skipped_events << { event: event, reason: "[skipped: destructive]" }
49
71
  else
50
72
  @replayed_events << event
51
- @shell.execute_input(cmd_text)
73
+ @shell.execute_input(cmd_text.to_s) if input_event
52
74
  end
53
75
  end
54
76
 
@@ -84,7 +84,7 @@ module Rubik
84
84
  "version" => existing["version"].to_i + 1, "updated_at" => now
85
85
  )
86
86
  else
87
- row = meta_next_row(meta, type)
87
+ row = allocate_row(meta, records, type)
88
88
  hash = content_hash(type, title, body, tags, links)
89
89
  { "id" => "#{type}.#{row}.#{hash[0, 16]}", "type" => type, "project" => @project,
90
90
  "row" => row, "hash" => hash, "title" => title.to_s, "body" => body.to_s,
@@ -94,10 +94,14 @@ module Rubik
94
94
 
95
95
  records = records.reject { |r| r["row"] == record["row"] } << record
96
96
  ensure_project_dirs
97
- write_records(type, records.sort_by { |r| r["row"].to_i })
98
97
  meta_bump_counts(meta, type) unless existing
99
98
  meta_set_ref(meta, ref, record["id"]) if ref
99
+ # Journal order (issue #562): commit the allocator state BEFORE the
100
+ # entity row. A crash between the two writes then costs a row number
101
+ # (harmless gap) instead of leaving a row on disk with a stale
102
+ # next_row — which the next put would reallocate and silently evict.
100
103
  save_meta(meta)
104
+ write_records(type, records.sort_by { |r| r["row"].to_i })
101
105
  touch_index(meta)
102
106
  record.dup
103
107
  end
@@ -318,11 +322,21 @@ module Rubik
318
322
  links.to_h { |k, v| [k.to_s, v.to_s] }.sort.to_h
319
323
  end
320
324
 
321
- def meta_next_row(meta, type)
325
+ # Row allocation reads BOTH the meta cursor and the on-disk rows.
326
+ # load_meta deliberately degrades to {} on corrupt/missing meta.json;
327
+ # deriving the next row from meta alone then reused row 1 and evicted
328
+ # the record already stored there (issue #562). A create is refused if
329
+ # the computed row is somehow already occupied — eviction is never an
330
+ # acceptable allocation strategy.
331
+ def allocate_row(meta, records, type)
322
332
  rows = (meta["next_row"] ||= {})
323
- rows[type] = rows[type].to_i + 1
333
+ disk_max = records.map { |r| r["row"].to_i }.max || 0
334
+ row = [rows[type].to_i, disk_max].max + 1
335
+ raise ArgumentError, "row #{row} already exists in #{type}; refusing to overwrite" if records.any? { |r| r["row"].to_i == row }
336
+
337
+ rows[type] = row
324
338
  meta["updated_at"] = Time.now.utc.iso8601
325
- rows[type]
339
+ row
326
340
  end
327
341
 
328
342
  def meta_bump_counts(meta, type)
@@ -62,7 +62,7 @@ module Rubik
62
62
 
63
63
  clean_path = path.to_s.strip
64
64
  clean_path = nil if clean_path.empty?
65
- eff_timeout = timeout.to_i if timeout&.to_i&.positive?
65
+ eff_timeout = timeout.to_i.clamp(1, 600) if timeout&.to_i&.positive?
66
66
 
67
67
  res = if clean_path || eff_timeout
68
68
  begin
@@ -112,17 +112,13 @@ module Rubik
112
112
  "relative to the project root (e.g. 'lib/app.rb', 'src/main.go', 'Gemfile').")
113
113
  end
114
114
 
115
- begin
116
- # NB: reset_baseline defaults to false on purpose. The buffer only
117
- # replaces the tracked baseline for files that have no baseline yet
118
- # (new files). Passing reset_baseline: true here would overwrite the
119
- # original baseline of an ALREADY-loaded file, defeating undo and
120
- # conflict restoration — the buffer could never restore the file's
121
- # true original state after a full overwrite.
122
- @buffer_manager.write(path, content)
123
- rescue ArgumentError
124
- @buffer_manager.write(path, content)
125
- end
115
+ # NB: reset_baseline defaults to false on purpose. The buffer only
116
+ # replaces the tracked baseline for files that have no baseline yet
117
+ # (new files). Passing reset_baseline: true here would overwrite the
118
+ # original baseline of an ALREADY-loaded file, defeating undo and
119
+ # conflict restoration — the buffer could never restore the file's
120
+ # true original state after a full overwrite.
121
+ @buffer_manager.write(path, content)
126
122
  "Successfully wrote to in-memory buffer: #{path}"
127
123
  rescue Errno::EACCES => e
128
124
  ToolOutput.error(DiagnosticReporter.render_permission_denied(path, operation: "write", reason: e.message))
@@ -186,7 +182,7 @@ module Rubik
186
182
  partial_note = IndexMessages.note_for(idx)
187
183
  # Path-filtered list drives the B9 explanation: an extension miss in
188
184
  # an INDEXED directory must read "no such files here", not "ignored".
189
- path_filtered = filter.empty? ? files.keys : files.keys.select { |f| f.start_with?(filter) }
185
+ path_filtered = filter.empty? ? files.keys : files.keys.select { |f| f == filter || f.start_with?("#{filter}/") }
190
186
  file_list = ext_filter && !ext_filter.empty? ? path_filtered.select { |f| f.end_with?(ext_filter) } : path_filtered
191
187
 
192
188
  return with_note(ignored_directory_message(filter, ext_filter), partial_note) if path_filtered.empty? && existing_but_unindexed?(@root_dir, filter)
@@ -66,7 +66,7 @@ module Rubik
66
66
  path_filter, outside_error = BaseTool.normalize_path_filter(path_filter, @root_dir)
67
67
  return ToolOutput.error(BaseTool.traversal_blocked_message(param(args, :path), @root_dir, context_index)) if outside_error
68
68
 
69
- case_sensitive = param(args, :case_sensitive, default: false)
69
+ case_sensitive = param(args, :case_sensitive, type: :flag, default: false)
70
70
  max_results = param(args, :max_results, type: :integer, default: 50)
71
71
  max_results = 50 if max_results <= 0
72
72
 
@@ -270,7 +270,8 @@ module Rubik
270
270
  def pass_path?(file_key, path_filter)
271
271
  return true if path_filter.empty?
272
272
 
273
- file_key.start_with?(path_filter.sub(%r{^\./}, ""))
273
+ filter = path_filter.sub(%r{^\./}, "")
274
+ file_key == filter || file_key.start_with?("#{filter}/")
274
275
  end
275
276
 
276
277
  def pass_extension?(file_key, ext_filter)
@@ -7,6 +7,35 @@ require_relative "../../platform"
7
7
 
8
8
  module Rubik
9
9
  module Tools
10
+ # Single source of truth for LSP DiagnosticSeverity (spec 3.17:
11
+ # 1=Error, 2=Warning, 3=Information, 4=Hint). Both the tool's human-facing
12
+ # output and the prompt builder's <diagnostic> tags map through here so a
13
+ # style hint can never be overstated as an error/warning (issue #546).
14
+ module LSPSeverity
15
+ # severity => [canonical label (prompt), display label (tool output)]
16
+ SEVERITIES = {
17
+ 1 => ["error", "ERROR"].freeze,
18
+ 2 => ["warning", "WARN"].freeze,
19
+ 3 => ["info", "INFO"].freeze,
20
+ 4 => ["hint", "HINT"].freeze
21
+ }.freeze
22
+ DEFAULT = SEVERITIES[4]
23
+
24
+ module_function
25
+
26
+ def entry(severity)
27
+ SEVERITIES.fetch(severity.to_s.to_i, DEFAULT)
28
+ end
29
+
30
+ def label(severity)
31
+ entry(severity)[0]
32
+ end
33
+
34
+ def display(severity)
35
+ entry(severity)[1]
36
+ end
37
+ end
38
+
10
39
  class BaseLSPTool < BaseTool
11
40
  REQUIRES = [Rubik::Coeffects::LSP_MANAGER].freeze
12
41
 
@@ -107,7 +136,7 @@ module Rubik
107
136
  end
108
137
  lines << "\nFile: #{fpath} (#{diags.size}; #{freshness}):"
109
138
  diags.each do |d|
110
- sev = d["severity"] == 1 ? "ERROR" : "WARN"
139
+ sev = LSPSeverity.display(d["severity"])
111
140
  start_line = (d.dig("range", "start", "line") || 0) + 1
112
141
  lines << " • [#{sev}] Line #{start_line}: #{d['message']}"
113
142
  end
@@ -137,12 +166,7 @@ module Rubik
137
166
  end
138
167
  lines = ["=== LSP Diagnostics for #{path} (#{diags.size} issue(s); #{freshness}) ==="]
139
168
  diags.each do |d|
140
- sev = case d["severity"]
141
- when 1 then "ERROR"
142
- when 2 then "WARN"
143
- when 3 then "INFO"
144
- else "HINT"
145
- end
169
+ sev = LSPSeverity.display(d["severity"])
146
170
  range = d["range"] || {}
147
171
  start_line = (range.dig("start", "line") || 0) + 1
148
172
  start_char = (range.dig("start", "character") || 0) + 1
@@ -36,7 +36,7 @@ module Rubik
36
36
  name: "show_file", aliases: ["show"],
37
37
  description: "Read a stored entity (review report, plan, goal snapshot, note...) from the central " \
38
38
  "storage database. As the ROOT agent, the full content renders DIRECTLY to the user's " \
39
- "terminal and you only get a one-line stub — use it for 'show/göster' requests instead of " \
39
+ "terminal and you only get a one-line stub — use it for 'show' requests instead of " \
40
40
  "read_file + re-echoing. In a subagent context the full content loads into YOUR context " \
41
41
  "like read_file (terminal rendering is the root agent's job). Accepts rubik://storage " \
42
42
  "URIs only, including refs form 'rubik://storage/<project>/refs/<alias>'.",
@@ -332,13 +332,13 @@ module Rubik
332
332
  previous_origin = previous_tool ? @tool_registry.origin(name) : nil
333
333
  @tool_registry.register(tool_instance, origin: :synthesis)
334
334
 
335
- # Register inverse in Runtime Context. When hot-updating an existing
336
- # overlay/MCP/synthesized tool, the inverse restores the previous
337
- # instance instead of leaving a hole in the toolbelt.
335
+ # One keyed inverse restores the previous instance on hot-update.
338
336
  ctx = active_context
339
337
  if ctx.respond_to?(:on_dispose) || ctx.respond_to?(:register_disposable)
340
338
  hook = ctx.respond_to?(:on_dispose) ? :on_dispose : :register_disposable
341
- ctx.send(hook) do
339
+ prior = (@synthesis_inverses ||= {})[name]
340
+ ctx.unregister_disposable(prior) if prior && ctx.respond_to?(:unregister_disposable)
341
+ @synthesis_inverses[name] = ctx.send(hook) do
342
342
  if previous_tool && @tool_registry.respond_to?(:swap)
343
343
  @tool_registry.swap(name, previous_tool, origin: previous_origin || :overlay)
344
344
  else
@@ -20,7 +20,7 @@ module Rubik
20
20
  # StepExecutor::ERROR_PREFIXES (kept as an alias there).
21
21
  ERROR_PREFIXES = [
22
22
  "-- ", "Error:", "Error ", "Usage:", "Pre-flight verification failed",
23
- "Bilinmeyen komut", "Failed", "Security blocked", "Command error",
23
+ "Unknown command", "Bilinmeyen komut", "Failed", "Security blocked", "Command error",
24
24
  "[EXIT ", "Test run [FAILED]", "Lint [FAILED]", "[CONFLICT]", "[CONFLICT "
25
25
  ].freeze
26
26
 
@@ -16,7 +16,7 @@ module Rubik
16
16
  return nil unless Capability.interactive?(input: shell.input, output: shell.output)
17
17
 
18
18
  routed = Statusline.current_route(shell)
19
- model = routed ? Statusline.model_label(routed) : "model yapılandırılmamış"
19
+ model = routed ? Statusline.model_label(routed) : "model not configured"
20
20
  project = File.basename(shell.buffer_manager&.root_dir || Dir.pwd)
21
21
  branch = shell.detect_git_branch || "no-git"
22
22
 
@@ -24,13 +24,13 @@ module Rubik
24
24
  "🎲 Rubik v#{Rubik::VERSION}",
25
25
  theme.paint(model, :info),
26
26
  theme.paint("#{project} · #{branch}", :dim),
27
- theme.paint("!help komutlar · ctrl+c kes · !config ayarlar", :dim)
27
+ theme.paint("!help commands · ctrl+c interrupt · !config settings", :dim)
28
28
  ]
29
29
 
30
30
  if Rubik::Platform.linux? && Rubik::Platform.which("bwrap") &&
31
31
  !Rubik::Storage::Layout.config_get(shell.config, "sandbox.enabled", false) &&
32
32
  Rubik::Storage::Layout.config_get(shell.config, "sandbox.prompt_on_startup", true)
33
- lines << theme.paint("💡 Linux & bwrap algılandı: '!sandbox on' ile donanımsal OS izolasyonu açılabilir", :warn)
33
+ lines << theme.paint("💡 Linux & bwrap detected: hardware OS isolation can be enabled with '!sandbox on'", :warn)
34
34
  end
35
35
 
36
36
  Frame.draw(
@@ -34,10 +34,12 @@ module Rubik
34
34
  choices = options.uniq.dup
35
35
  choices << "Other (write-in response)" if allow_custom
36
36
 
37
- answer = p.select("Seçiminizi yapın / Select an option:", choices, filter: true, per_page: 10)
37
+ answer = p.select("Select an option:", choices, filter: true, per_page: 10)
38
38
  if answer == "Other (write-in response)"
39
- custom = p.ask("Yanıtınız / Your answer:")
40
- custom.to_s.strip.empty? ? options.first : "Other (write-in): #{custom.strip}"
39
+ custom = p.ask("Your answer:")
40
+ # An empty write-in is "no selection" — never bind the
41
+ # model-authored first option as the user's choice (#559).
42
+ custom.to_s.strip.empty? ? nil : "Other (write-in): #{custom.strip}"
41
43
  else
42
44
  answer
43
45
  end
@@ -57,9 +59,10 @@ module Rubik
57
59
 
58
60
  render_card(question, multi: true)
59
61
  p = build_prompt
60
- answers = p.multi_select("Seçenekleri belirleyin / Select options (Space: toggle, Enter: confirm):",
62
+ answers = p.multi_select("Select options (Space: toggle, Enter: confirm):",
61
63
  options.uniq, filter: true, per_page: 10)
62
- answers.empty? ? [options.first] : answers
64
+ # An empty confirmation means no selection, not the first option (#559).
65
+ answers
63
66
  rescue Interrupt, StandardError
64
67
  :cancelled
65
68
  ensure
@@ -80,11 +83,11 @@ module Rubik
80
83
  def render_card(question, multi: false)
81
84
  return unless @shell&.output
82
85
 
83
- subtitle = multi ? "Çoklu Seçim (Boşluk: Seç/Kaldır · Enter: Onayla)" : "Tekli Seçim (Ok tuşları: Gezin · Enter: Onayla)"
86
+ subtitle = multi ? "Multi-Select (Space: Select/Deselect · Enter: Confirm)" : "Single-Select (Arrow keys: Navigate · Enter: Confirm)"
84
87
  card = Frame.draw(
85
88
  [@theme.paint(question, :bold), @theme.paint(subtitle, :dim)],
86
89
  theme: @theme,
87
- title: @theme.paint("#{@theme.glyph(:action)} AJAN SORUSU", :accent)
90
+ title: @theme.paint("#{@theme.glyph(:action)} AGENT QUESTION", :accent)
88
91
  )
89
92
  @shell.output.puts(card)
90
93
  end
@@ -50,23 +50,23 @@ module Rubik
50
50
  # keypress uses the same raw-mode path as every other UI surface.
51
51
  def offer_actions(shell, theme)
52
52
  prompt = Approvals.build_prompt(shell)
53
- key = prompt.keypress(theme.paint(" a: uygula (!apply) · q veya enter: çık ", :dim))
53
+ key = prompt.keypress(theme.paint(" a: apply (!apply) · q or enter: exit ", :dim))
54
54
  apply_all(shell) if key.to_s.strip.downcase == "a"
55
55
  rescue Interrupt
56
56
  Rubik::REPL::InterruptHandler.restore_console_after_interrupt
57
57
  rescue StandardError => e
58
58
  # apply! fails loud on containment breaks and IO errors — the user
59
59
  # pressed "a", so the verdict must reach them, not vanish here.
60
- shell.output.puts "\n[Hata] Uygulama başarısız: #{e.message}"
60
+ shell.output.puts "\n[Error] Apply failed: #{e.message}"
61
61
  end
62
62
 
63
63
  def apply_all(shell)
64
64
  applied = shell.buffer_manager.apply!
65
65
  if applied.empty?
66
- shell.output.puts "Uygulanacak değişiklik kalmadı."
66
+ shell.output.puts "No changes left to apply."
67
67
  else
68
68
  shell.sync_context_and_ast(applied)
69
- shell.output.puts "Uygulandı: #{applied.join(', ')}"
69
+ shell.output.puts "Applied: #{applied.join(', ')}"
70
70
  end
71
71
  end
72
72